Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

c# - System.Windows.Forms.Keys.HasFlag behaving weirdly

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, KeyEventArgs e)
{
    if (e.KeyData.HasFlag(Keys.Enter))
    {
        e.SuppressKeyPress = true;
    }
}

It really does prevent Enter from being inserted, but strangely enough it prevents other keys from being inserted as well. So far we've discovered that the keys: 'O', 'M', '/' and '-' are also being "caught".

Update: The following code does what I need:

private void m_commentMemoEdit_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyValue == (int)Keys.Return)
  {
    e.SuppressKeyPress = true;
  }
}

But I still don't understand the former code does not work and this does.

I've looked at the System.Windows.Forms.Keys enum but didn't find any clues (though I must say this is one weirdly constructed enum). Can anyone explain why is this happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...