Sending keyboard events to DirectX application from C# RRS feed

  • Question

  • Hello,

    I am writing some code in c# to enable me to send keyboard input to a third party DirectX application.

    I am able to use :

            // Get a handle to an application window.
            [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
            public static extern IntPtr FindWindow(string lpClassName,
                IntPtr WindowName);

            // Activate an application window.
            public static extern bool SetForegroundWindow(IntPtr hWnd);

    To get a handle to application window, and set it to be the foreground application, but the SendKeys methods fail to send the keyboard events to the application, ie:


    does not raise a new dialog as expected. Pressing K on the keyboard however does. I have also tried the

            static extern bool SendMessage(IntPtr hWnd, uint msg, int wParam, int lParam);

            static extern byte VkKeyScan(char ch);

    methods to accomplish this, by calling:

     const uint WM_KEYDOWN = 0x100;
     SendMessage(handle, WM_KEYDOWN, VkKeyScan('K'), 0);

    which does not yield any results either.

    However both methods seem to work fine with other applications such as Notepad, Calculator etc.

    I have been reading up on the issue and it seems that the only way to do what I want is by using DirectInput events. I could not however find a concrete example on how to use them.  Which methods/dlls would I have to import to do this ?

    I'd appreciate any help, as I'm getting close to the point of bursting into tears!!!

    Friday, July 31, 2009 2:46 PM


  • Unfortunately, most DirectX applications don't use the standard message pump to handle keyboard events.  They usually check for key state in their own game loop, which is done differently.  This tends to break SendKeys or SendMessage attempts to send input.

    The best option is typically to use the SendInput function instead.  This is going to be a bit trickier from C#, but the required info is posted on pinvoke.net .
    Reed Copsey, Jr. - http://reedcopsey.com
    • Marked as answer by Harry Zhu Friday, August 7, 2009 6:04 AM
    Friday, July 31, 2009 4:36 PM