c# - 键盘事件只作用一次

标签 c# winapi keyboard-events wndproc

我正在尝试制作简单的键重映射器 - 当按下一个键盘键时,代码生成另一个不同的键。这是我的代码:

[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);
        }

问题是,当我按下分配给 id 2 的热键时,此按键返回码每 30 秒只能工作一次。这个 keybd_even winapi 函数有什么问题?我用错了吗? wndProc中的其他东西(ids)没有问题,只有keybd_event有问题。

最佳答案

问题出在错误的 KeyUp 和 KeyDown 函数上。 以下是正确的函数:

[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);
}

关于c# - 键盘事件只作用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15544182/

相关文章:

c# - "Transparent"Windows 窗体在 DirectDraw Video Surface 前面时闪烁

C# 相当于 ruby​​ 的字符串后继方法 ("abcd".succ -> "abce")

c++ - WSARecv 的 dsBytes、dwFlags 参数

c++ - 什么标题包含 HR 功能定义? ( window 编程)

c++ - 如何编写垂直右侧的 IE 资源管理器栏

silverlight - 当应用程序处于全屏模式时,无法在 Silverlight 3 中使用键盘输入文本框控件

c# - 关于 AverageTimer32 PerformanceCounter 的困惑

c# - for 循环中的集合值更改

java - 重新定义 JRadioButton 中 Tab 键的行为?

macos - 为什么“Key Down 事件掩码”不起作用,但“全部掩码”却起作用?