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

In my specific case, I am trying to create an application that sends keyboard keystrokes to DosBox (dos-games emulator, not the Windows command line).

I tried to do this using SendKeys, but this does not work because DosBox is not an application that processes Windows messages (this was explained to me by the exception).

I am currently trying to do this using the keyboard, for example: The first method is the one that receives keystrokes and transfers them to the next application (for example, 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);
    }

However, calling the CallNextHookEx () function throws an access violation exception.

What do I need to think about here?

+4
2

, LPARAM , ..

SetWindowsHookEx(WH_KEYBOARD_LL,...)

KBDLLHOOKSTRUCT, , . , . ( , , WPARAM WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN WM_SYSKEYUP.)

, , Marshal.ReadInt32(lParam) key code, , .

, SendInput, times it not .


( SendInput)

+4

, "keybd_event" "SendKeys".

public static class Keyboard
{
    public static void Press(Keys keys, int sleep = 1)
    {
        var keyValue = (byte)keys;

        NativeMethods.keybd_event(keyValue, 0, 0, UIntPtr.Zero); //key down

        Thread.Sleep(sleep);

        NativeMethods.keybd_event(keyValue, 0, 0x02, UIntPtr.Zero); //key up
    }
}

internal static partial class NativeMethods
{
    [DllImport("user32.dll")]
    internal static extern void keybd_event(byte bVk, byte bScan, int dwFlags, UIntPtr dwExtraInfo);
}
0

All Articles