In my specific case, I'm trying to create an application that sends keyboard keystrokes to the DosBox (the dos-games emulator, not the windows command prompt).
I tried doing it using SendKeys but that does not work because DosBox is not an application that processes windows-messages (an exception told me that).
At the moment I'm trying to do that using a keyboard hook, like this: The first method is the one which receives hooked keystrokes and puts them through to the next application (like in this example)
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
return CallNextHookEx(hookId, nCode, wParam, lParam);
}
private void GenerateKeyPress()
{
int vkCode = (int)Keys.Up; //My chosen key to be send to dosbox
IntPtr lParam = new IntPtr(vkCode);
IntPtr wParam = new IntPtr(255);
CallNextHookEx(hookId, 0, wParam, lParam);
}
The CallNextHookEx() function call however throws an access violation exception.
What do I need to think of here?
The access violation is caused by the fact that LPARAM
for a low-level keyboard hook, that is, one created with
SetWindowsHookEx(WH_KEYBOARD_LL,...)
is a pointer to a KBDLLHOOKSTRUCT
, not a keycode masquerading as a pointer. You're telling the next hook in the hook chain to access an arbitrary memory location. (Also, the WPARAM
is supposed to be one of WM_KEYDOWN
, WM_KEYUP
, WM_SYSKEYDOWN
, or WM_SYSKEYUP
.)
The example code you linked, uses Marshal.ReadInt32(lParam)
to get the key code, which is actually reading the first integer in the structure referenced by the pointer.
As far as what you're trying to accomplish, the way to do it would be to use SendInput
which is a topic that's been covered here so many times that it does not bear repeating.
(That's not even all the SendInput questions)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With