问题
Now I've been trying to create a similar functionality as there is in Push-To-Talk voice chat applications, but so far I couldn't find any fitting solutions to this. I am not using MFC or CLR.
The problem is quite simple. My window should be usually out of focus (ie minimized etc), but I need to react to keypresses (basically, I don't even want to know if the button is being held down or not). Unfortunately, WM_KEYDOWN only works if the window has keyboard focus. I do know that for example Teamspeak uses DirectInput for this, but I'm also aware that it can definitely be done without it as well, which I'd highly prefer.
The only other solution that I could make work is polling with GetAsyncKeyState, but it looks like this is far from being a good solution either. If at all possible, I'd still prefer using Windows messages.
回答1:
The problem can be solved either with RegisterHotKey or with a global low-level keyboard hook.
RegisterHotKey
(which Cody Gray suggested in the commends) is probably the more suitable choice here.
回答2:
I agree with Jon. Use user32.dll and the RegisterHotKey function. Very useful example code is located at: https://www.codeproject.com/kb/cs/kiosk_cs.aspx?display=print
If, like I initially was, the code looks like complete gibberish and you have no idea what to do, watch the tutorials: https://www.youtube.com/watch?v=qQWqGOaZiFI They're very useful!
If you try to register a system hotkey: However note that the code from the first link would return an error, depending on what system hotkey you try to register. My question on this which highlights the issue: How do you disable system hotkeys in user32.dll? (currently unsolved). There is also a code edit there that will fix one of the errors you will get, if you try to override system hotkeys:
[DllImport("user32.dll", SetLastError = true)]
I did manage to block the Windows + E hotkey, but others like Alt + F4 and Home + Right did not get disabled and would return an error.
This should not be an issue for you if you do not try to override a system hotkey. I would however suggest you use the code below to diagnose your code, if one of your hotkeys fails to register.
Marshal.GetLastWin32Error()
^ Full context on that line of code is in the first link!
来源:https://stackoverflow.com/questions/5259322/catching-global-hotkeys-windows