System.Windows.Forms.Keys.HasFlag behaving weirdly

后端 未结 3 548
悲哀的现实
悲哀的现实 2020-12-22 00:52

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         


        
3条回答
  •  遥遥无期
    2020-12-22 01:11

    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.

提交回复
热议问题