问题
I'm trying to create a program with some key bindings (F1-F12) which will pick up the key presses while out of focus (specifically, while a game is running).
Is there anyway to detect these key presses without using a global hook? The language I am programming in (real studio) doesn't have a means of creating a DLL (required for a global hooks), plus, I'm hoping of having it cross platform with mac (which is what realstudio does).
回答1:
While as klartex says, a low-level keyboard/mouse hook does not require a DLL (unlike all other types of hooks), a hook of any kind is certainly overkill for what you're trying to accomplish.
All you need is the RegisterHotKey function, which allows you to register any key (or combination of keys) as a system-wide hotkey. This fulfills your requirement of being able to pick up the key presses even while your application is out of focus.
As a bonus, RegisterHotKey
does not require a DLL nor is it as "heavy" as a system-wide hook. Hooks have a negative effect on performance; you shouldn't see that with RegisterHotKey
.
Once you've registered a hot key by calling the function, you handle WM_HOTKEY messages inside of your application's window procedure. Once you're finished, make sure that you call the UnregisterHotKey function to unregister your application as handling that hot key.
The only caveat here is mentioned in the documentation:
The F12 key is reserved for use by the debugger at all times, so it should not be registered as a hot key. Even when you are not debugging an application, F12 is reserved in case a kernel-mode debugger or a just-in-time debugger is resident.
But the same issue would apply if you were installing a low-level keyboard hook. F12 is just not a good candidate hot key, regardless of the application. If you absolutely must, use it at your own risk.
回答2:
With this you should be able to hook keyboard without DLL on windows: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644985%28v=vs.85%29.aspx
回答3:
RegisterHotKey does not require a dll.
来源:https://stackoverflow.com/questions/8562006/keyboard-hooks-without-using-a-dll