尝试将C# Windows窗体中的焦点更改按钮从Tab键更改为Enter键。

huangapple go评论51阅读模式
英文:

trying to change the focus change button from tab to enter in c# windows forms

问题

以下是翻译好的部分:

"所以如标题所述,我试图将标签按钮更改为回车按钮。我已经写了这个代码,它有点起作用,但当在按钮上按下回车时,它会触发按钮而不是改变焦点。每次按回车键时都会播放声音。如何禁用回车键功能?"

英文:

so as the title says im trying to change the tab button into enter button. i wrote this already and it kinda works

public class EnterBasedForm : System.Windows.Forms.Form
{
    public EnterBasedForm()
    {
        KeyPreview = true;
        KeyUp += new KeyEventHandler(OnKeyPressed);
    }

    public void OnKeyPressed(object? sender, KeyEventArgs handler)
    {
        if (handler.KeyCode == Keys.Enter)
        {
            SendKeys.Send("{TAB}");
        }
    }
}

but when getting on a button this presses the button instead of changing the focus. and each time pressing enter it plays a sound. how can i disable the enter key functionallity?

答案1

得分: 2

你可以在 ProcessCmdKey() 中捕获回车键,使用 base.ProcessTabKey() 强制生成一个制表键,然后通过返回 true 来消耗回车键,以防止它继续传递:

public partial class EnterBasedForm : Form
{

    public EnterBasedForm()
    {
        InitializeComponent();
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            base.ProcessTabKey(true);
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }

}
英文:

You can capture the Enter key in ProcessCmdKey(), force a Tab key with base.ProcessTabKey(), and then consume the Enter key so it doesn't go further by returning true:

public partial class EnterBasedForm : Form
{

    public EnterBasedForm()
    {
        InitializeComponent();
    }

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            base.ProcessTabKey(true);
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }

}

huangapple
  • 本文由 发表于 2023年5月25日 18:15:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331184.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定