Fire button click event using a key combination in c#

佐手、 提交于 2019-12-10 10:25:29

问题


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

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.

Any ideas?

Many Thanks


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/8924728/fire-button-click-event-using-a-key-combination-in-c-sharp

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