在C#Windows窗体应用程序中捕获Ctrl+Shift+P键笔划

本文关键字:Ctrl+Shift+P C#Windows 窗体 应用程序 | 更新日期: 2023-09-27 18:10:21

可能重复:
捕获Windows窗体应用程序中的组合键事件

当按下(Ctrl+Shift+p(键时,我需要执行特定操作。

如何在我的C#应用程序中捕获此信息?

在C#Windows窗体应用程序中捕获Ctrl+Shift+P键笔划

我个人认为这是最简单的方法。

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control && e.Shift && e.KeyCode == Keys.P)
        {
            MessageBox.Show("Hello");
        }
    }

以下不仅是在窗体上捕获击键的方法,而且实际上是添加全局Windows快捷方式的方法。

1.导入所需的顶级库:

// DLL libraries used to manage hotkeys
[DllImport("user32.dll")] public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")] public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

2.在Windows窗体类中添加一个字段,该字段将作为代码中热键的参考:

const int MYACTION_HOTKEY_ID = 1;

3.注册热键(例如在Windows窗体的构造函数中(:

// Modifier keys codes: Alt = 1, Ctrl = 2, Shift = 4, Win = 8
// Compute the addition of each combination of the keys you want to be pressed
// ALT+CTRL = 1 + 2 = 3 , CTRL+SHIFT = 2 + 4 = 6...
RegisterHotKey(this.Handle, MYACTION_HOTKEY_ID, 6, (int)'P');

4.通过在Windows窗体类中添加以下方法来处理键入的密钥:

protected override void WndProc(ref Message m) {
    if (m.Msg == 0x0312 && m.WParam.ToInt32() == MYACTION_HOTKEY_ID) {
        // My hotkey has been typed
        // Do what you want here
        // ...
    }
    base.WndProc(ref m);
}

您可以将KeyDownEvent与lambda事件处理程序一起使用:

以下是有关KeyDown的更多信息。阅读这篇文章,思考一下你想要这种行为的范围。

this.KeyDown += (object sender, KeyEventArgs e) =>
{
    if (e.Control && e.Shift && e.KeyCode == Keys.P)
    {
        MessageBox.Show("pressed");
    }
};

通过p/Invoke使用GetKeyboardState API。它返回一个数组,表示Windows识别的每个虚拟密钥的状态。如果我没有错的话,您可以将Keys枚举强制转换为一个字节,并将其用作索引,如下所示:

byte[] keys = new byte[256];
GetKeyboardState(keys);
bool isCtrlPressed = (keys[(byte)Keys.ControlKey] == 1);

-

资源:

  • p/Invoke定义

  • MSDN文档:GetKeyboardState函数