How to use KeyPressEvent in correct way

前端 未结 2 1340
情话喂你
情话喂你 2021-01-20 07:33

try to create HotKeys for my forms

code

    private void FormMain_KeyPress(object sender, KeyPressEventArgs e)        
    {
        if (e.KeyChar ==         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-20 07:41

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

提交回复
热议问题