英文:
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论