Problem with keybd_event()

Hello,

I am using keybd_event to simulate keyboard in applications. Function works perfect in notepad, calc, all windows, etc. but in some directx program it is getting error. On some computers it can type keys but on some others it can not. I have no idea what to do to fixt it or what is missing on those computers.

Anyone has ever met this problem or know how to fix it please

Btw that's a part of source

[DllImport("user32.dll")]
private static extern void keybd_event(
byte bVk,
byte bScan,
uint dwFlags,
IntPtr dwExtraInfo
);

private void keybd_press(byte bVk)
{
keybd_event(bVk, 0, 0, new System.IntPtr());
keybd_event(bVk, 0, KEYEVENTF_KEYUP, new System.IntPtr());
}



Answer this question

Problem with keybd_event()

  • SJ0775

    After re-reading the documentation I see that SendMessage waits until the specified window has finished processing the message, whereas PostMessag simply returns without waiting. Is that your reason for using one vs. the other
  • Guruprasad Hathwar

    Hi Quirm, in my own experiences in this area I found that just sending the wm_keydown and wm_keyup events was more reliable with DirectX applications. Here is some of the interop code:

    public void SendKey(ushort key, IntPtr hWnd)

    {

    SetActiveWindow(hWnd);

    SendMessage(hWnd, WM_KEYDOWN, key, 0);

    SendMessage(hWnd, WM_KEYUP, key, 0);

    }

    [DllImport("user32.dll")] //Set the active window

    public static extern IntPtr SetActiveWindow(IntPtr hWnd);

    [DllImport("user32.dll")] //sends a windows message to the specified window

    public static extern int SendMessage(IntPtr hWnd, int Msg, uint wParam, int lParam);

    //API Constants

    public const ushort WM_KEYDOWN = 0x0100;

    public const ushort WM_KEYUP = 0x0101;

    Hope that helps,

    Dennis



  • Krutika

    I did all of this quite a while ago but yeah I think that's why I chose Send over Post in this case.  I probably tried it both ways and found Send to be more reliable for what I was doing.

    Yes the ushort param is the virtual key code for the key.



  • chris441962

    Dennis - Is there any particular reason you didn't use PostMessage   I'm looking at the documentation for the two functions and am not seeing why a person would choose one over the other.  Just wondering.

    Also, is the key parameter (passed to SendMessage in SendKey()) sill the virtual-key code for a given key   This was the case for keybd_event.  Again, the documentation for SendMessage isn't really clear on this issue as far as I can tell. 

    (Perhaps I should find better documentation!)

    Thanks.


  • Michael Mroch

    Thanks a lot for your reply. It works great.
  • Problem with keybd_event()