使用相同访问键的焦点按钮而不是触发第一个

Focus buttons with same access key instead of firing the first

按下 Alt+B 触发 第一个按钮,尽管按钮 2 具有相同的访问权限关键。

如何在第一个 Alt+Bfocus 按钮 1 和在第二个 focus 按钮 2 Alt+B 上不处理按键事件或类似事件?

private void button1_Click(object sender, EventArgs e)
{
    System.Media.SystemSounds.Beep.Play();
}

private void button2_Click(object sender, EventArgs e)
{
    System.Media.SystemSounds.Hand.Play();
}

您可以覆盖 ProcessMnemonic 以自定义按下助记符时按钮的行为。在处理助记符时,当你检测到控件处于应该根据助记符执行动作的状态时,returntrue,否则returnfalse.

在下面的实现中,控件首先检查助记符是否属于控件,如果不属于Focuded则调用Focus和return为真,否则(它是集中的或者它不应该处理助记符)returns false。这样它允许焦点在具有相同助记符的控件之间移动:

using System.Windows.Forms;

public class MyButton:Button
{
    protected override bool ProcessMnemonic(char charCode)
    {
        if (this.UseMnemonic && this.Enabled && this.Visible &&
            Control.IsMnemonic(charCode, this.Text))
        {
            if (!this.Focused)
            {
                this.Focus();
                return true;
            }
        }
        return false;
    }
}