是否有一种简单的方法可以在类似于visual studio中的winforms应用程序中捕获 ctrl + key1 , key2 事件,例如 ctrl + e , c =注释掉选定的行?
我目前正在覆盖我的表单OnKeyDown
事件:
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Control && e.KeyCode.ToString() == "N")
{
//do something...
}
}
答案 0 :(得分:2)
评论中的文章可能是针对WPF的,但其中的想法仍然可以使用
构建一个类,例如
public class MultiKeyGesture
{
private List<Keys> _keys;
public MultiKeyGesture(IEnumerable<Keys> keys, Keys modifiers)
{
_keys = new List<Keys>(keys);
if (_keys.Count == 0)
{
throw new ArgumentException("At least one key must be specified.", "keys");
}
}
private int currentindex;
public bool Matches(KeyEventArgs e)
{
if (_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;
}
答案 1 :(得分:1)
如果你只有两个关键的快捷键,比如VS,你可以存储在变量中按下的最后一个键。
private Keys lastKeyPressed = null;
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if(e.Control && lastKeyPressed != null)
{
if(lastKeyPressed == Keys.firstKey && e.KeyCode == Keys.secondKey)
{
}
else if (...) // so on and so forth.
}
else if(e.Control)
lastKeyPressed = e.KeyCode;
}
protected override void OnKeyUp(KeyEventsArgs e)
{
if(!e.Control)
lastKeyPressed = null;
}
这将执行两个键快捷键,并在释放ctrl键时重置它。这只是未经测试的伪代码,但它的概念是在保持Ctrl时保存最后按下的键,然后在我尝试传达的ctrl被释放时重置它。
答案 2 :(得分:0)
调用e.Modifiers作为控制键,并调用e.KeyCode作为组合键。
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
// For Tow Key Shortcut.
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.B)
{}
// For Triple Key Shortcut.
if (e.Modifiers.ToString() == (Keys.Shift+", "+Keys.Control) && e.KeyCode == Keys.B)
{}
}
// For Form level Key events you must have to set KeyPreview to True;
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
}