[英]how to detect two hot key in win form app like CTRL +C , CTRL+ W
my question is how to detect two hot keys in win form application CTRL + C , CTRL , K like visual studio commenting command 我的问题是如何像Visual Studio注释命令一样在Win窗体应用程序CTRL + C , CTRL , K中检测两个热键
I need to simulate VS hot key For commenting a line of code 我需要模拟VS热键来注释一行代码
Simple way is... There is a Windows API Function called ProcessCmdKey, by overriding this function we can achieve what we want 简单的方法是...有一个名为ProcessCmdKey的Windows API函数,通过重写此函数,我们可以实现所需的功能
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Control | Keys.C)) {
MessageBox.Show("You have pressed the shortcut Ctrl+C");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Microsoft Documentation can be found here 可以在这里找到Microsoft文档
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.C)
{
}
}
if you want to handle Ctrl + C followed by Ctrl + K you need to maintain a state variable. 如果你要处理Ctrl + C 键 ,然后按Ctrl + K,你需要保持状态变量。
Set the Form KeyPreview
property to true
and handle the Form KeyDown
event. 将Form KeyPreview
属性设置为true
并处理Form KeyDown
事件。
Try This: 尝试这个:
this.KeyPreview=true;
private bool isFirstKeyPressed= false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
isFirstKeyPressed = true;
}
if (isFirstKeyPressed)
{
if (e.Control && e.KeyCode == Keys.K)
{
MessageBox.Show("Ctrl+C and Ctrl+K pressed Sequentially");
/*write your code here*/
isFirstKeyPressed= false;
}
}
}
private bool _isFirstKeyPressedW = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control & e.KeyCode == Keys.W)
{
_isFirstKeyPressedW = true;
}
if (_isFirstKeyPressedW)
{
if (e.Control & e.KeyCode == Keys.S)
{
//write your code
}
else
{
_isFirstKeyPressedW = e.KeyCode == Keys.W;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.