问题描述
尝试为我的表单创建热键
try to create HotKeys for my forms
代码
private void FormMain_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
MessageBox.Show("e");
}
}
适用于一个键,但是如果我想使用CTRL + N之类的键组合,请尝试使用if (e.KeyChar == (char)Keys.Enter && e.KeyChar == (char)Keys.N)
-但它不起作用.我是对的-使用这样的代码进行按键组合吗?
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 + Enter-捕获CTRL而不是Enter键-尝试创建其他if
,但-结果相同...
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...
将事件从KeyPress
更改为KeyDown
-现在可以正常工作
Change event from KeyPress
to KeyDown
- now it's work
推荐答案
对于Control
和另一个字母的其他组合,有趣的是,e.KeyChar
将具有不同的代码.例如,通常e.KeyChar = 'a'
的代码为97
,但是在按a
(或A
)之前按Control
时,实际代码为1
.因此,我们有这段代码可以处理其他组合:
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:
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
}
您也可以为此目的使用KeyDown
事件. (实际上,KeyDown
更合适).因为它支持KeyData
,其中包含修饰键和另一个文字键的组合信息:
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:
private void FormMain_KeyDown(object sender, KeyEventArgs e){
//Pressing Control + N
if(e.KeyData == (Keys.Control | Keys.N)) MessageBox.Show("e");
}
这篇关于如何正确使用KeyPressEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!