switch keys vs if else if

  • Thread starter Thread starter pixel
  • Start date Start date
P

pixel

hi
i just discovered something strange

when i use in ProcessCmdKey
this construction

switch(keyData)
{
case Keys.Left:
{
...
}break;
case Keys.Right:
{
...
}break;
}

everuthing is fine
but in this construction

if((keyData & Keys.Left) == Keys.Left)
{
...
}
else if ((keyData & Keys.Right) == Keys.Right)
{
...
}

program goes into "left" no matter if i press left or right arrow
why?

keys up and down and other work fine

pixel

ps
debuger shows propper values in keyData
 
pixel said:
i just discovered something strange

when i use in ProcessCmdKey
this construction

switch(keyData)
{
case Keys.Left:
{
...
}break;
case Keys.Right:
{
...
}break;
}

everuthing is fine
but in this construction

if((keyData & Keys.Left) == Keys.Left)
{
...
}
else if ((keyData & Keys.Right) == Keys.Right)
{
...
}

program goes into "left" no matter if i press left or right arrow
why?

keys up and down and other work fine

Because the Keys enumeration isn't meant to be used like that. The
value of Keys.Left is 37, and the value of Keys.Right is 39. Look at
the bit patterns:

Keys.Left = 00100101
Keys.Right= 00100111

So Keys.Right & Keys.Left is in fact Keys.Left. Everything is happening
as it should be - it's just that your test doesn't do what you think it
should.
 
pixel said:
so if i wanna check shift with left/right
i have to neg shift bits right?

You should use:

if ((key & Keys.KeyCode)==Keys.Left)
{
// It's a "left" key press
}

and

if ((key & Keys.Modifier & Keys.Shift)==Keys.Shift)
{
// The shift key is down
}
 
thx very much

pixel


Jon Skeet said:
You should use:

if ((key & Keys.KeyCode)==Keys.Left)
{
// It's a "left" key press
}

and

if ((key & Keys.Modifier & Keys.Shift)==Keys.Shift)
{
// The shift key is down
}
 
Back
Top