C# 使 Enter 键的行为就像按下了按钮一样
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19573399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Making it so the Enter Key behaves as if a button has been pressed
提问by user2867035
How do I code it so that when the enter key has been pressed it behaves as if a button on the existing form has been pressed?
我该如何编码,以便在按下 Enter 键时,它的行为就像按下了现有表单上的按钮一样?
Let's say the button on the form makes it so a display message of hello shows up
假设表单上的按钮使它显示 hello 的显示消息
private void buttonHello_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello");
}
How do I make it so when the enter key is pressed it does the same thing (for the life of me I can't remember and it's probably really simple and I'm being really dumb)
我如何做到这样当按下回车键时它会做同样的事情(对于我的生活我不记得了,这可能真的很简单而且我真的很笨)
回答by Idle_Mind
WinForms? If yes, select the FORM. Now change the AcceptButton property to "buttonHello".
WinForms?如果是,请选择表格。现在将 AcceptButton 属性更改为“buttonHello”。
See Form.AcceptButton:
Gets or sets the button on the form that is clicked when the user presses the ENTER key.
获取或设置窗体上当用户按下 ENTER 键时单击的按钮。
回答by Rahul Tripathi
Are you looking for something like this:-
你在寻找这样的东西吗:-
private void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
button.PerformClick();
}
回答by Jonesopolis
回答by Karl Anderson
Capture the Enterkey down event, like this:
捕获Enter按键按下事件,如下所示:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter){
button.PerformClick();
}
}
回答by Felice Pollano
You are driving toward the "Magic Button" antipattern, and the symptom is that you want to drive the butto from somewhere else. Insulate the behavior you want from the button in some way ( a member function could work ) and then call the same function from any point you like.
If you really just want to reply to the enter key, best way is, as suggested by @Idle_mind, use the AcceptButton
.
您正在朝着“魔术按钮”反模式前进,症状是您想从其他地方驱动按钮。以某种方式将您想要的行为与按钮隔离(成员函数可以工作),然后从您喜欢的任何点调用相同的函数。如果您真的只想回复回车键,最好的方法是,如@Idle_mind 所建议的那样,使用AcceptButton
.
回答by ó?th Manē
In your Form properties, set AcceptButton = yourButton, That's it.
在您的表单属性中,设置 AcceptButton = yourButton,就是这样。
回答by Marco Concas
For WinForms:
对于 WinForms:
using System.Windows.Forms; // reference
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// do something
}
}
For WPF:
对于 WPF:
using System.Windows.Input; // reference
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
// do something
}
}
Notes
笔记
- This example is for Enter button, you can easy change that changing
Keys.YOURKEY
. - You need to add first the event in your form or window.
- 此示例用于 Enter 按钮,您可以轻松更改该更改
Keys.YOURKEY
. - 您需要先在表单或窗口中添加事件。