Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Keys Enumeration Confused: Keys.Alt or Keys.RButton | Keys.ShiftKey | Keys.Alt

Tags:

c#

enums

I was trying to test whether the Alt key was pressed.

I had a check similar to:

private void ProcessCmdKey(Keys keyData)
{
 if (keyData == Keys.Alt)
 {
  System.Console.WriteLine ("Alt Key Pressed");
 } 
}

Anyways needless to say when I breakpointed when I had pressed the Alt key the debugger told me the key that was pressed was actually Keys.RButton | Keys.ShiftKey | Keys.Alt

Can anyone shed some light on what is going on or perhaps point me to an article that can explain?

Thanks FZ

Edit: I am still a bit lost as to why the ENUM would have have other bit values set and not simply the Alt key? I understand that the enum can include more than 1 state with the flags attrivbute but I am not sure why it does if all I pressed was Alt?

like image 744
Setheron Avatar asked Sep 02 '09 18:09

Setheron


3 Answers

If you want to test whether Alt is part of the pressed keys, you can perform a bitwise test;

if((keyData & Keys.Alt) == Keys.Alt) {...}
like image 56
Marc Gravell Avatar answered Nov 09 '22 02:11

Marc Gravell


Keys is a Flags Enumeration. This means it can have more than one value at a given time. You should check it like so:

if ( (keyData & Keys.Alt) == Keys.Alt)
{
   // Alt was pressed!
}
like image 4
Reed Copsey Avatar answered Nov 09 '22 02:11

Reed Copsey


Enum with FlagsAttribute are implemented using bits.
See this link for a good start - http://msdn.microsoft.com/en-us/library/cc138362.aspx

EDIT: Are you pressing RIGHT (mouse button) with Shift key during the operation, to select/highlight something, while debugging?

like image 1
shahkalpesh Avatar answered Nov 09 '22 02:11

shahkalpesh