C# 如何以正确的方式使用 KeyPressEvent
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19076051/
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
How to use KeyPressEvent in correct way
提问by gbk
try to create HotKeys for my forms
尝试为我的表单创建热键
code
代码
private void FormMain_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
MessageBox.Show("e");
}
}
works for one key, but if I whant to use combination of keys like CTRL+N, try to use if (e.KeyChar == (char)Keys.Enter && e.KeyChar == (char)Keys.N)
- but it's not working. I'm I right - using such code for keys combination?
适用于一个键,但如果我想使用像 CTRL+N 这样的键组合,请尝试使用if (e.KeyChar == (char)Keys.Enter && e.KeyChar == (char)Keys.N)
- 但它不起作用。我是对的 - 使用这样的代码进行组合键?
EDIT
编辑
This code capture only first pressed key, but not combination - so if I press CTRL + Enter - code capture CTRL but not Enter Key - try to create additional if
but - result the same...
此代码仅捕获第一个按下的键,而不是组合键 - 因此,如果我按 CTRL + Enter - 代码捕获 CTRL 但不是 Enter 键 - 尝试创建其他if
但 - 结果相同...
Change event from KeyPress
to KeyDown
- now it's work
将事件从 更改KeyPress
为KeyDown
- 现在可以使用了
采纳答案by King King
For other combinations of Control
and another letter, there is an interesting thing that, the e.KeyChar
will have different code. For example, normally e.KeyChar = 'a'
will have code of 97
, but when pressing Control
before pressing a
(or A
), the actual code is 1
. So we have this code to deal with other combinations:
对于Control
和另一个字母的其他组合,有一件有趣的事情,即e.KeyChar
会有不同的代码。例如,通常e.KeyChar = 'a'
会有 代码97
,但Control
在按下a
(或A
)之前按下时,实际代码是1
。所以我们有这个代码来处理其他组合:
private void FormMain_KeyPress(object sender, KeyPressEventArgs e)
{
//Pressing Control + N
if(e.KeyChar == 'n'-96) MessageBox.Show("e");
//Using this way won't help us differentiate the Enter key (10) and the J letter
}
You can also use KeyDown
event for this purpose. (In fact, KeyDown
is more suitable). Because it supports the KeyData
which contains the combination info of modifier keys and another literal key:
您也可以KeyDown
为此目的使用事件。(其实KeyDown
更合适)。因为它支持KeyData
包含修饰键和另一个文字键的组合信息的 :
private void FormMain_KeyDown(object sender, KeyEventArgs e){
//Pressing Control + N
if(e.KeyData == (Keys.Control | Keys.N)) MessageBox.Show("e");
}
回答by Kurubaran
try this for combination of Ctrl+ N,
试试这个Ctrl+ 的组合N,
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.N)
{
MessageBox.Show("e");
}