Fire button click event using a key combination in c#

余生长醉 提交于 2019-12-05 22:24:09

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);
    }

Where MyButton is assumed to be your custom button control class.

Samuel Slade

I'm assuming you are using WinForms, given that the ampersand character is used in WinForms control captions to denote the shortcut character. If that is the case, then you can use the Button.PerformClick() method on a WinForms Button in order to fire the Click event manually.

If this is not the case and you are, in fact, using WPF; then take a look at the link Dmitry has posted in his comment for WPF Input Bindings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!