110,565
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// 新建一个空白Winform工程,添加以下代码:
bool controlE = false;
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ((keyData & Keys.Control) == Keys.Control)
{
if ((keyData & Keys.E) == Keys.E)
{
controlE = true;
return true;
}
else if ((keyData & Keys.C) == Keys.C && controlE)
{
MessageBox.Show("Control E+C");
}
}
controlE = false;
return base.ProcessCmdKey(ref msg, keyData);
}
}
public class MyShortCut
{
public Keys Modifier { get; private set; }
public Keys[] Sequence { get; private set; }
public Action Action { get; private set; }
static TypeConverter converter = TypeDescriptor.GetConverter(typeof(Keys));
public MyShortCut (Keys modifier, string keys, Action action)
{
this.Modifier = modifier;
this.Sequence = keys.Split(',')
.Select(x => (Keys)converter.ConvertFrom(x))
.ToArray();
this.Action = action;
}
public MyShortCut(Keys modifier, string keys, ToolStripMenuItem menuItem) :
this(modifier, keys, menuItem.PerformClick)
{
string ms = converter.ConvertTo(modifier, typeof(string)).ToString().Replace("+None","");
menuItem.ShortcutKeyDisplayString = ms + "+" + keys;
}
private List<Keys> keysPressed = new List<Keys>();
private bool ProcessCmdKey(Keys keyData)
{
if ((keyData & this.Modifier) == this.Modifier)
{
this.keysPressed.Add(keyData & Keys.KeyCode);
if (keysPressed.SequenceEqual(Sequence.Take(keysPressed.Count)))
{
if (keysPressed.Count == Sequence.Length)
{
this.Action();
keysPressed.Clear();
}
return true;
}
}
keysPressed.Clear();
return false;
}
public static class Manager
{
static List<MyShortCut> shortcuts = new List<MyShortCut>();
public static void Register(MyShortCut shortcut)
{
shortcuts.Add(shortcut);
}
public static bool ProcessCmdKey(ref Message msg, Keys keyData)
{
bool processed = false;
foreach (var shortcut in shortcuts)
{
processed = shortcut.ProcessCmdKey(keyData) || processed;
}
return processed;
}
}
}
使用方法(其中if(true)示范给菜单加组合快捷键):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
MyShortCut.Manager.Register(new MyShortCut(Keys.Control, "E,C", () => MessageBox.Show("Control EC")));
MyShortCut.Manager.Register(new MyShortCut(Keys.Alt, "E,E", () => this.Text += " EE"));
if (true)
{
ToolStripMenuItem subItem = new ToolStripMenuItem("Hi", null, (o, ea) => MessageBox.Show("hi"));
ToolStrip tool = new ToolStrip(new ToolStripMenuItem("About", null, subItem));
this.Controls.Add(tool);
MyShortCut.Manager.Register(new MyShortCut(Keys.Control, "H,I", subItem));
}
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
return MyShortCut.Manager.ProcessCmdKey(ref msg, keyData) || base.ProcessCmdKey(ref msg, keyData);
}
}
如果你还想在代码上简洁一些,可以使用Winform的"扩展属性"(类似在设计窗口中设置ToolTip的方式)。
具体可以参考微软的例子:https://msdn.microsoft.com/zh-cn/library/d6c1xa43.aspx
不过,即使用了扩展属性,示例中的protected override bool ProcessCmdKey还是不能避免。这是因为亲疏有别,微软对自己菜单的快捷键有特别处理。