如何使用按键来运行方法?
我的表单有几个按钮,例如“扫描”和“退出”。我在许多程序中看到按钮可以通过按键使用。很多时候,要按下的唯一键在按钮上的文本中带有下划线(我不知道如何在这些论坛上使用下划线选项!)。我转到表单并添加了一个按键事件:
private void Form1_KeyPress(object sender, KeyPressEventArgs key)
{
switch (key.ToString())
{
case "s":
Run_Scan();
break;
case "e":
Application.Exit();
break;
default:
MessageBox.Show("I'll only accept 's' or 'e'.");
break;
}
}
但是按表单上的“s”或“e”不会执行任何操作。不知道我哪里出错了?
My form has several buttons such as "Scan" and "Exit". I have seen in many programs where buttons will be useable by keypress. Lots of times the unique key to press is underlined in the text on the button (I don't know how to use an underline option on these forums!). I went to the form and added a keypress event:
private void Form1_KeyPress(object sender, KeyPressEventArgs key)
{
switch (key.ToString())
{
case "s":
Run_Scan();
break;
case "e":
Application.Exit();
break;
default:
MessageBox.Show("I'll only accept 's' or 'e'.");
break;
}
}
But then pressing 's' or 'e' on the form doesn't do anything. Not sure where I'm going wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
重写 ProcessKeyCommand 将接受来自表单上任何位置的输入。但是,您应该添加修饰符,因为例如在文本框中按“s”或“e”也会触发该操作。
Overriding ProcessKeyCommand will accept input from anywhere on the form. You should add a modifier however, since pressing 's' or 'e' in a textbox, for example, will also trigger the action.
我认为您正在寻找所谓的访问密钥:有定义通过“&”象征。
摆脱 KeyPress 事件处理程序。你不会需要它。
将按钮的文本更改为“&Scan”和“&Exit”。
另外: 以下是有关在 Windows 应用程序中使用访问键的一些准则.
I think you are looking for what are called Access Keys: There are defined by the '&' symbol.
Get rid of your KeyPress event handler. You will not need it.
Change the text of your buttons to "&Scan" and "&Exit".
Also: Here are some guidelines about using access keys in windows applications.
key.ToString()
是错误的调用方法。您想要访问密钥属性:key.KeyChar
。有关详细信息,请参阅 MSDN 此处 KeyPressEventArgs,其中包括示例。
key.ToString()
is the wrong method to call. You want to access the key property:key.KeyChar
.See the MSDN here for more info on the KeyPressEventArgs, which includes examples.
您可以在按钮的 Text 属性中在要为按钮创建热键的字母前面放置一个 & 符号。您可以从表单设计器的“属性”窗格中设置“文本”属性,也可以通过编程方式进行设置。以下是程序化方法的示例。
You can put an ampersand in front of the letter you want to make a hot key for the button in the Text property of your button. You can set the Text property from the Properties pane in the form designer, or you can set it programmatically. Below is an example of programmatic approach.