在C#Windows窗体应用程序中捕获Ctrl + Shift + P键击
可能重复:
捕获Windows窗体应用程序中的组合键事件
我需要在按下( Ctrl + Shift + P )键时执行特定操作。
如何在我的C#应用程序中捕获它?
我个人认为这是最简单的方法。
private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.Shift && e.KeyCode == Keys.P) { MessageBox.Show("Hello"); } }
您可以将KeyDownEvent与lambda事件处理程序一起使用:
以下是有关KeyDown的更多信息 。 阅读文章并考虑您希望获得此行为的范围。
this.KeyDown += (object sender, KeyEventArgs e) => { if (e.Control && e.Shift && e.KeyCode == Keys.P) { MessageBox.Show("pressed"); } };
以下不仅是一种捕获表单上击键的方法,而且实际上是一种添加全局Windows快捷方式的方法。
1.在您的class级顶部导入所需的库:
// 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); }
通过P / Invoke使用GetKeyboardState API。 它返回一个数组,表示Windows识别的每个虚拟键的状态。 如果我没有弄错,你可以将Keys枚举转换为一个字节并将其用作索引,如下所示:
byte[] keys = new byte[256]; GetKeyboardState(keys); bool isCtrlPressed = (keys[(byte)Keys.ControlKey] == 1);
–
资源:
上述就是C#学习教程:在C#Windows窗体应用程序中捕获Ctrl + Shift + P键击分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/950513.html