[英]Capturing ctrl + multiple key downs
是否有一種簡單的方法可以在類似於 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...
}
}
評論里的文章可能是針對WPF的,但是里面的想法還是可以用的
構造一個類,例如
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;
}
如果您只有兩個快捷鍵,就像 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 釋放時重置它。
為控制鍵調用 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.