Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .net send keys NOT using SendKey() but rather with hooking mabye

Tags:

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?

like image 819
Ravior Metal Avatar asked Jun 14 '16 18:06

Ravior Metal


1 Answers

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)

like image 66
theB Avatar answered Sep 28 '22 02:09

theB