【问题标题】:Perform Click on a Toolbar Button when I press Enter当我按 Enter 时执行单击工具栏按钮
【发布时间】:2011-03-09 09:50:27
【问题描述】:

(ToolStripButton 作为表单的 AcceptButton)

我有以下问题:

在我的表单中,我有一个工具栏,并且希望默认情况下 Enter 按下操作不与标准 OK 按钮相关联,而是与 OK 工具栏按钮(ToolStripButton )。

为了实现这一点,我需要实现IButtonControl 接口,我在下面这样做

代码:

public class MyTSB : System.Windows.Forms.ToolStripButton, IButtonControl
{
    public MyTSB()
        : base()
    {
    }

    DialogResult _DialogResult = DialogResult.None;
    public DialogResult DialogResult
    {
        get { return _DialogResult; }
        set { _DialogResult = value; }
    }

    bool isDefault = false;
    public void NotifyDefault(bool value)
    {
        this.isDefault = value;
    }

    protected virtual new void PerformClick()
    {
       // ???
    }

    void IButtonControl.PerformClick()
    {
        // ???
        this.OnClick(EventArgs.Empty);
    }
}

问题在于PerformClick 函数。一方面,这个功能已经存在于ToolStripButton中,另一方面,我从来没有实现“点击”(设置为Form的acceptButton)工具条按钮......

怎么了?

【问题讨论】:

    标签: .net winforms


    【解决方案1】:

    您也可以像这样覆盖FormProcessCmdKey-Method:

    protected override bool ProcessCmdKey(
            ref System.Windows.Forms.Message msg,
            System.Windows.Forms.Keys keyData)
    {
        switch (keyData) {
            case Keys.Return:
                this.yourToolStripButton.PerformClick();
                break;
    
            default:
                return base.ProcessCmdKey(ref msg, keyData);
        }
    
        return true;
    }
    

    【讨论】:

    • 您的代码运行良好(您只是在最后一个函数中忘记了“ref”)。但是,我想知道我尝试做的替代实现。
    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    相关资源
    最近更新 更多