I have the following code, meant to prevent user from writing new-lines in a memo text editor:
private void m_commentMemoEdit_KeyDown(object sender, KeyEvent
HasFlags() is inherited from Enum.HasFlags(). It is useful on enums that are declared with the [Flags] attribute. It uses the & operator to do a test on bit values. Trouble is, Keys.Enter is not a flag value. Its value is 0x0d, 3 bits are set. So any key that has a value with bits 0, 2 or 3 turned on is going to return true. Like Keys.O, it has value 0x4f. 0x4f & 0x0d = 0x0d so HasFlags() returns true.
You should only use it with Keys values that actually represent flag values. They are Keys.Alt, Keys.Control and Keys.Shift. Note that these are modifier keys. So you can use HasFlags to see the difference between, say, F and Ctrl+F.
To detect Keys.Enter you should do a simple comparison. As you found out. Note that your if() statement is also true for Alt+Enter, etcetera, this might not be what you want. Instead use
if (e.KeyData == Keys.Return) e.SuppressKeyPress = true;
Which suppresses the Enter key only if none of the modifier keys are pressed.
I suspect it has something to do with the underlying values of the System.Windows.Forms.Keys
enum being mapped directly to the keyboard codes, which are not always mutually exclusive. The documentation says that you should not use any kind of bitwise operation on them, and gives an example of why not (Beware the FlagsAttribute on the enum!).
MSDN also says that the HasFlag
function returns the result of this: thisInstance And flag = flag
, so you could potentially set a breakpoint and look at the actual binary codes coming in and see if that operation would give you a true for the set of keys you listed.
In the end, your updated code is the right way to do what you want to do.
HasFlag is for Flags - which means if a bit is set or not
the keyvalue is an ordinal value, so completely different from flags use the comparison operator and everything should be fine.
some enum fields are defined like flags, e.g.
enum SomeFlag
{
BitOne = 1,
BitTwo = 2,
Bitthree = 4
};
here it makes sense to use "HasFlag"