How to use KeyPressEvent in correct way

38,010

Solution 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 
}

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");
}

Solution 2

try this for combination of Ctrl + N,

if (e.Modifiers == Keys.Control && e.KeyCode == Keys.N)
   {
      MessageBox.Show("e");
   }
Share:
38,010
hbk
Author by

hbk

BOYCOTT on russia - don't buy, sell, support

Updated on September 30, 2020

Comments

  • hbk
    hbk over 3 years

    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?

    EDIT

    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...


    Change event from KeyPress to KeyDown - now it's work