I'm trying to create a program where I can press a hotkey while I'm in a game and the program will receive the key press and preform an action. I've tried following tutorials and looking at other questions, but they seem to not provide the functionality I want or the methods are outdated and I cannot use them without error.
Asked
Active
Viewed 87 times
1 Answers
2
You'll need to do this with WINAPI Interop. The technique is usually referred to as a global hook.
You'll want to handle the WM_KEYDOWN
, WM_KEYUP
, WM_SYSKEYDOWN
, and WM_SYSKEYUP
events. You can read up on WPF and Win32 specific interoperation here.
You can read up on planform invoke (PInvoke) here. Pinvoke is how you call unmanaged / native functions implemented in a dll from your .NET application.
For example, you can call the SetWindowsHookEx
(Pinvoke) | (MSDN) method in the user32.dll to install an application hook.
IntPtr hHook;
using (Process process = Process.GetCurrentProcess())
using (ProcessModule module = process.MainModule)
{
IntPtr hModule = GetModuleHandle(module.ModuleName);
hHook = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, hook, hModule, 0);
}
You can find Pinvoke signatures at this wiki site: http://www.pinvoke.net
Here is a minimal keyboard hook example.
Here is an example C# / WPF example that could help you get started.