[英]How to use the DataGridView's Keydown event and check what key was pressed?
I have this really simple block of code: 我有这个非常简单的代码块:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
AddRow();
if (e.KeyCode == Keys.Back && dataGridView1.SelectedRows.Count > 0)
RemoveRow();
}
Then when I step through my code and hit either Delete
or Backspace
, this is the value of e.KeyCode: 然后,当我单步执行代码并单击
Delete
或Backspace
,这是e.KeyCode的值:
I know my code doesn't check for Delete
but I can add that in simply afterwards. 我知道我的代码不会检查
Delete
但是我可以在之后简单地添加。
If I cast KeyCode
to a string, it gives me the value "Delete" but I shouldn't have to do that... 如果我将
KeyCode
转换为字符串,它会为我提供“ Delete”值,但我不必这样做...
edit; 编辑; I should note that my first block of code, for Ctrl-V works perfectly fine.
我应该注意,对于Ctrl-V来说,我的第一段代码非常完美。 So I don't understand why e.KeyCode doesn't evaluate to Keys.Delete or Keys.Backspace?
所以我不明白为什么e.KeyCode不能评估为Keys.Delete或Keys.Backspace?
edit 2; 编辑2; My coworker found something that could be 100% coincidental, or extremely interesting.
我的同事发现这可能是100%偶然的,或者是非常有趣的。
KeyCode.Delete
= 46. KeyCode.Space
= 32 KeyCode.Back
= 8 KeyCode.MButton
= 4; KeyCode.Delete
= KeyCode.Space
= 32 KeyCode.Back
= 8 KeyCode.MButton
= 4; KeyCode.RButton
= 2; KeyCode.RButton
= 2;
32 + 8 + 4 + 2 = 46. I feel like some tinfoil hat conspiracy theorist for thinking this might be on to something, but we're completely baffled. 32 + 8 + 4 + 2 =46。我觉得有些锡箔帽子阴谋论者认为这可能是某种原因,但我们完全感到困惑。
From MSDN , "This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values"
从MSDN来说 ,
"This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values"
What you see is string representation of the enum value. 您将看到枚举值的字符串表示形式。 It uses
Flags
attribute to construct the string in Enum.ToString()
method. 它使用
Flags
属性在Enum.ToString()
方法中构造字符串。 See this SO question for more clarification. 见这更多的澄清SO问题。
Back
is the enumeration value that indicates the backspace key was pressed ( MSDN-Keys Enumeration ). Back
是表示按下了退格键的枚举值( MSDN-Keys Enumeration )。 Example code: 示例代码:
if (e.KeyCode.HasFlag(Keys.Back)) {
//do stuff here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.