System.Windows.Forms.Keys.HasFlag表现异常 [英] System.Windows.Forms.Keys.HasFlag behaving weirdly

查看:40
本文介绍了System.Windows.Forms.Keys.HasFlag表现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,旨在防止用户在备忘录文本编辑器中写换行符:

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;
    }
}

它确实确实阻止了Enter的插入,但是奇怪的是,它也阻止了其他键的插入.到目前为止,我们发现键"O","M","/"和-"也被捕获".

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.

我查看了 System.Windows.Forms.Keys 枚举,但没有找到任何线索(尽管我必须说这是一个奇怪构造的枚举).谁能解释为什么会这样?

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?

推荐答案

HasFlags()继承自Enum.HasFlags().对于用[Flags]属性声明的枚举很有用.它使用&操作员对位值进行测试.麻烦的是,Keys.Enter不是标志值.它的值为0x0d,设置了3位.因此, any 键的值已打开的0、2或3位将返回true.像Keys.O一样,它的值为0x4f.0x4f&0x0d = 0x0d,因此HasFlags()返回true.

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.

您应仅将其与实际上代表标志值的键值一起使用.它们是Keys.Alt,Keys.Control和Keys.Shift.请注意,这些是修饰符键.因此,您可以使用HasFlags查看F和Ctrl + F之间的区别.

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.

要检测密钥,请输入一个简单的比较.如您所知.请注意,对于Alt + Enter等,您的if()语句也适用,这可能不是您想要的.改为使用

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;

只有在没有按下任何修改键的情况下,才会抑制Enter键.

Which suppresses the Enter key only if none of the modifier keys are pressed.

这篇关于System.Windows.Forms.Keys.HasFlag表现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆