捕获 ctrl + 多个按键 [英] Capturing ctrl + multiple key downs
本文介绍了捕获 ctrl + 多个按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种简单的方法可以在类似于 Visual Studio 中的 winforms 应用程序中捕获 ctrl+key1、key2 事件,例如ctrl+e, c = 注释掉选中的行?
Is there an easy way to capture a ctrl+key1, key2 event in a winforms app similar to that in visual studio such as ctrl+e, c = comment out selected lines?
我目前正在覆盖我的表单 OnKeyDown
事件:
I am currently overriding my forms OnKeyDown
event:
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Control && e.KeyCode.ToString() == "N")
{
//do something...
}
}
推荐答案
评论里的文章可能是针对WPF的,但是里面的想法还是可以用的
The article in the comment may have been for WPF but the idea in it can still be used
构造一个类,例如
public class MultiKeyGesture
{
private List<Keys> _keys;
private Keys _modifiers;
public MultiKeyGesture(IEnumerable<Keys> keys, Keys modifiers)
{
_keys = new List<Keys>(keys);
_modifiers = modifiers;
if (_keys.Count == 0)
{
throw new ArgumentException("At least one key must be specified.", "keys");
}
}
private int currentindex;
public bool Matches(KeyEventArgs e)
{
if (e.Modifiers == _modifiers && _keys[currentindex] == e.KeyCode)
//at least a partial match
currentindex++;
else
//No Match
currentindex = 0;
if (currentindex + 1 > _keys.Count)
{
//Matched last key
currentindex = 0;
return true;
}
return false;
}
}
但忽略继承.
使用它
private MultiKeyGesture Shortcut1 = new MultiKeyGesture(new List<Keys> { Keys.A, Keys.B }, Keys.Control);
private MultiKeyGesture Shortcut2 = new MultiKeyGesture(new List<Keys> { Keys.C, Keys.D }, Keys.Control);
private MultiKeyGesture Shortcut3 = new MultiKeyGesture(new List<Keys> { Keys.E, Keys.F }, Keys.Control);
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (Shortcut1.Matches(e))
BackColor = Color.Green;
if (Shortcut2.Matches(e))
BackColor = Color.Blue;
if (Shortcut3.Matches(e))
BackColor = Color.Red;
}
这篇关于捕获 ctrl + 多个按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文