False keyvalues are passed on keydown event

浪子不回头ぞ 提交于 2019-12-11 23:43:12

问题


I have a MDI parent form. When user presses Enter I want the Application to shut down.

I check the keydown event as follows:

 private void MainForm_KeyDown(object sender, KeyEventArgs e)
 {

     if (e.KeyValue == (int)Keys.Enter) 
     {
                    Application.Exit();
     }
 }

Now it works fine, when I don't have any clickable controls on form (Button, TextBox etc). The e.KeyValue has the (int) value of Enter Key (13). But if I put some buttons or textboxes on to MDI Form, e.KeyValue brings the keyvalue of Alt Key i.e. 18. Why so ??

So now if I press Alt+Enter, the form closes; but not only on Enter Key

Thanks in advance


回答1:


You need to process the KeyPress a little sooner. The following code will work for you:

    protected override bool ProcessKeyPreview(ref System.Windows.Forms.Message m)
    {
        int _ENTER = 13;
        int _KEYUP = 257;
        if (m.Msg == _ENTER && (int)m.WParam == _KEYUP)
        {
            Application.Exit();
        }
        return base.ProcessKeyPreview(ref m);
    }



回答2:


Use e.KeyCode and e.Modifiers;



来源:https://stackoverflow.com/questions/5761877/false-keyvalues-are-passed-on-keydown-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!