[.net] Waiting For Keypress In WinForms App

Started by
4 comments, last by Headkaze 16 years, 9 months ago
I'm making a WinForms based game and I need to do some simple input code. Basically I have a button that, when pressed, puts the game into a loop until the user presses a button. I'm pretty new with general .NET programming, so I have no idea how to do this. Any suggestions or links or search keywords? Thanks in advance.
Advertisement
Forms are event based so you need to handle keydown or keyup events. I believe the first thing you need to do is turn on the KeyPreview property of the form. Then click the little thunderbolt icon in the properties dialog after clicking on your form. Scroll down to KeyDown or KeyUp event and double click on it, and it will create an event handler for you. In that event handler you can read when a user presses a key.

Eg.
private void Form1_KeyDown(object sender, KeyEventArgs e){    switch (e.KeyCode)    {        case Keys.Escape:            Application.Exit();            break;    }}
I know forms are event based, but is there no way to do polling? I don't want to use event based input here. When the user clicks a button, the application should just sit there waiting for a keypress. I suppose I'll just not use forms for this then. Not sure what else to use, but it seems silly that there isn't also a way to poll the keyboard.
Maybe you could use this:

[DllImport("User32.dll")]private static extern short GetAsyncKeyState( System.Windows.Forms.Keys vKey);


You can look up the GetAsyncKeyState function on and dll importing on msdn if you need to see how it works, but you should be able to call that function at any time to check if a key is down.
[opinion]
I think what you are thinking about doing is a really bad idea. If you put in a loop polling for a keystroke then you are going to be taking 100% of the CPU doing absolutely nothing. I know if it was a program on my system doing this I would be one very unhappy person.

What I don't understand is why you are trying to do it this way. Yes it is a game but it is running within forms. Forms have a very good event system to avoid the very problem you are trying so hard to create.

theTroll
[/opinion]
Quote:Original post by TheTroll
[opinion]
I think what you are thinking about doing is a really bad idea. If you put in a loop polling for a keystroke then you are going to be taking 100% of the CPU doing absolutely nothing. I know if it was a program on my system doing this I would be one very unhappy person.

What I don't understand is why you are trying to do it this way. Yes it is a game but it is running within forms. Forms have a very good event system to avoid the very problem you are trying so hard to create.

theTroll
[/opinion]


I totally agree. Just use the Windows message system the way it was intended. It will be more than enough for your needs.

This topic is closed to new replies.

Advertisement