开发者

How can I accept keystrokes in a WinForms app?

How do I accept keystrokes? For example, I want to quit the application if the user presses q.

How do I go about doing this? I a开发者_开发技巧m using WinForms.


Use the KeyDown or KeyUp events if you are using WinForms.

For example, just drop the following code into your form class to override the OnKeyUp event and close whenever the user presses the q key:

protected override void OnKeyUp(KeyEventArgs e)
{
    if (e.KeyCode == Keys.Q)
    {
        this.Close();
    }

    base.OnKeyUp(e);
}


What kind of application you are making? Window Forms? WPF? Console? In the first two there are events related to key presses, in the third one, you can use Console.Read or ReadLine methods and test the return value


You may want to use KeyPreview and OnKeyPreview here, depending on what controls are you using on the form. Sometimes, KeyDown and KeyUp will be handled before you get a chance to handle them yourself.

BTW, for windows apps, using 'q' key without any modifiers to quit isn't such a great idea, since you might have textboxes on the form that accept input, and your app will quit if someone writes 'quebec' into the textbox.

And if you don't want to use events, then OVERRIDE same virtual methods and provide implementation for them that will do what you want. But again, preferred method here is with events.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜