使用C#中的组合键来触发按钮单击事件 [英] Fire button click event using a key combination in c#
问题描述
我创建了一个从常规.Net按钮派生的自定义按钮,并添加了以下属性以添加快捷键组合:
I've created custom button derived from a normal .Net button and have added the following property to add a short cut key combination:
public Keys ShortCutKey { get; set; }
我希望此组合触发按钮的click事件,但不知道将按钮放置在窗体上时如何实现此操作.我知道执行按钮快捷方式的标准方法是使用&在快捷方式字符之前,但我需要使用组合键.
I want this combination to fire the click event of the button but have no idea how to implement this when the button is placed on a form. I know the standard way of doing a button shortcut is to use the & before the short cut character but I need to use a key combination.
有什么想法吗?
非常感谢
推荐答案
重写表单的ProcessCmdKey()方法以检测快捷键.像这样:
Override the form's ProcessCmdKey() method to detect shortcut keystrokes. Like this:
private bool findShortCut(Control.ControlCollection ctls, Keys keydata) {
foreach (Control ctl in ctls) {
var btn = ctl as MyButton;
if (btn != null && btn.ShortCutKey == keydata) {
btn.PerformClick();
return true;
}
if (findShortCut(ctl.Controls, keydata)) return true;
}
return false;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (findShortCut(this.Controls, keyData)) return true;
return base.ProcessCmdKey(ref msg, keyData);
}
假设MyButton是您的自定义按钮控件类.
Where MyButton is assumed to be your custom button control class.
这篇关于使用C#中的组合键来触发按钮单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!