Search code examples
c#keyboarddirectx

Sending Key to Game-(Fullscreen)-Application


I use the following Code to send Keystrokes to Windows:

[DllImport("user32.dll", SetLastError = true)]
private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

public const int KEYEVENTF_EXTENDEDKEY = 0x0001; //Key down flag 
public const int KEYEVENTF_KEYUP = 0x0002; //Key up flag 
keybd_event((byte)key, 0, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event((byte)key, 0, KEYEVENTF_KEYUP, 0);

"key" can be any keycode. Simple ones like a character or also Function Keys and so on.

This works fine in "simple" Application. For example If I open NotePad++ and my Program runs in the Background everything works as desired.

But when I open a fullscreen-game (e.g. Pinball FX) the Keystrokes do not seem to be received.

I expect that DirectX or something similar is the issue here. Is there another way to send Keys there? Maybe through SharpDX?


Solution

  • I managed to solve this by using a different approach using DirectInput as described here: https://www.codeproject.com/questions/279641/c-sharp-directinput-send-key

    [DllImport("user32.dll", SetLastError = true)]
            private static extern uint SendInput(uint numberOfInputs, INPUT[] inputs, int sizeOfInputStructure);
    
            private static void SendKeyDown(ushort keyCode)
            {
                var input = new KEYBDINPUT
                {
                    Vk = keyCode
                };
    
                SendKeyboardInput(input);
            }
    
            private static void SendKeyUp(ushort keyCode)
            {
                var input = new KEYBDINPUT
                {
                    Vk = keyCode,
                    Flags = 2
                };
                SendKeyboardInput(input);
            }
    
            private static void SendKeyboardInput(KEYBDINPUT keybInput)
            {
                INPUT input = new INPUT
                {
                    Type = 1
                };
                input.Data.Keyboard = keybInput;
    
                if (SendInput(1, new[] { input }, Marshal.SizeOf(typeof(INPUT))) == 0)
                {
                    throw new Exception();
                }
            }