try to create HotKeys for my forms
code
private void FormMain_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar ==
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
}
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");
}
try this for combination of Ctrl + N,
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.N)
{
MessageBox.Show("e");
}