Archived

This topic is now archived and is closed to further replies.

knallbunt

c# onkeypress

Recommended Posts

hi i''m currently moving some simple programs from c++ to c# for practice but i''m having some problems with the onkeypress method in c#.. ESC, Space and some other keys seem to work well but Arrow Keys and minuscule letter keys don''t work.. for example: protected override void OnKeyPress (System.Windows.Forms.KeyPressEventArgs e) { if ((int)(byte)e.KeyChar == (int)System.Windows.Forms.Keys.W /* or ...Keys.Left for example*/ ) /* do something here*/ } only works when i press shift + w.. but i want a reaction to ''w'' when i write e.KeyChar == ''w'' it works but i still can''t get any arrow keys to work properly thanks in advance

Share this post


Link to post
Share on other sites
Try using this...

protected override bool ProcessDialogKey(Keys keyData)
{
MessageBox.Show(keyData.ToString());
return base.ProcessDialogKey (keyData);
}

or atleast something like it.

Share this post


Link to post
Share on other sites
The problem is simple.

e.KeyChar is a char.

Therefore use
if(e.KeyChar == 'w' || e.KeyChar == 'W') {...}

Also, try looking at overriding
OnKeyDown(KeyEventArgs e) and OnKeyUp(KeyEventArgs e)

then you can do
if(e.KeyData == System.Windows.Forms.Keys.W){...}

And with that, you’ll know when the key has been pressed, and when it has been released, which is usually nicer for games

Also you need to override IsInputKey if you are going to use ProcessDialogKey
Like so


protected override bool IsInputKey(Keys keyData)
{
switch(keyData)
{
case Keys.Up: return false;
case Keys.Down: return false;
case Keys.Right: return false;
case Keys.Left: return false;
}
return base.IsInputKey (keyData);
}




[edited by - Sei on March 18, 2004 9:50:30 PM]

Share this post


Link to post
Share on other sites
So, you can see that KeyPress can only handle characters. While this limitation does not create a fuss for small and simple applications, most applications require the proper handling of all keys, not just alphanumeric and punctuation mark keys. The KeyDown event allows you to capture function keys, but not arrow keys. The KeyUp event lets you capture all keys, but this event is only triggered when the user releases the key, by which time it is probably too late to handle the key pressing. The next technique we can resort to is the ProcessDialogKey method, which enables us to capture all keys.

found this here: http://www.ondotnet.com/pub/a/dotnet/2002/04/29/keys.html?page=2

but ProcessDialogKey works like a charm. Thanks for your answers much appreciated

Share this post


Link to post
Share on other sites