.NET enum.HasFlag() bug?

CrazyTea

I'm using the following .NET 4.5.2 code:

if (this.ContainsFocus && keyData == (Keys.Tab|Keys.Shift))
{ ... }

Why is the expression true when ContainsFocus (bool = true) and keyData (System.Windows.Forms.Keys) is Keys.O | Keys.Shift?

As you can see the breakpoint is hit:

breakpointscreenshot

with this values:

watchscreenshot

A workaround for this bug (?!) is:

if (this.ContainsFocus && (int)keyData == (int)(Keys.Tab|Keys.Shift))
{ ... }
jmc

No, HasFlag does not have a bug. Unfortunately, the .NET FlagsAttribute is all or nothing and System.Windows.Forms.Keys is defined in such a way that only Keys.Modifiers may be used as flags.

From https://msdn.microsoft.com/en-us/library/system.windows.forms.keys%28v=vs.110%29.aspx

The Keys class contains constants for processing keyboard input. The members of the Keys enumeration consist of a key code and a set of modifiers combined into a single integer value. In the Win32 application programming interface (API) a key value has two halves, with the high-order bits containing the key code (which is the same as a Windows virtual key code), and the low-order bits representing key modifiers such as the SHIFT, CONTROL, and ALT keys.

As a result, you can check any of the modifiers (Keys.Shift, Keys.Alt, Keys.Control) with HasFlag, but nothing else.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related