Вопрос

I am trying to make simple key remapper - when one keyboard key pressed, another different key press generated by code. Here is my code:

[DllImport("user32.dll")]
static extern uint keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
public static void KeyDown(System.Windows.Forms.Keys key)
{
   keybd_event((byte)key, 0, 0, 0);
}
public static void KeyUp(System.Windows.Forms.Keys key)
{
   keybd_event((byte)key, 0, 0x7F, 0);
}
 protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x0312)
            {
                int id = m.WParam.ToInt32();
                ...
                if (id==2) {
                  KeyDown(Keys.Return);
                    KeyUp(Keys.Return);     
                }  
                ...         
            }
            base.WndProc(ref m);
        }

Problem is, when I press hotkey assigned to id 2, this press return code works only once per maybe 30 seconds. Whats wrong with this keybd_evend winapi function? Did I use it wrong? There is nothing wrong with other things (ids) in wndProc, troubles with only keybd_event.

Это было полезно?

Решение

Poblem was in wrong functions KeyUp and KeyDown. Here are correct functions:

[DllImport("user32.dll")]
static extern uint keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
public static void KeyDown(System.Windows.Forms.Keys key)
{
      keybd_event((byte)key, 0x45, 0x0001 | 0, 0);
}

public static void KeyUp(System.Windows.Forms.Keys key)
{
      keybd_event((byte)key, 0x45, 0x0001 | 0x0002, 0);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top