Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

c# - False keyvalues are passed on keydown event

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...