如何确定是否在KeyPress事件中按下了Backspace? [英] How can I determine if the Backspace has been pressed in the KeyPress event?
问题描述
此:
http://msdn.microsoft.com/en-us /library/system.windows.forms.control.keypress.aspx
...表明我应该可以在KeyPress事件中访问e.KeyCode,但我似乎没有.我试图只允许1,2,3和退格键:
...indicates that I should have access to e.KeyCode in the KeyPress event, but I don't seem to. I'm trying to allow only 1,2,3, and backspace:
private void textBoxQH1_KeyPress(object sender, KeyPressEventArgs e) {
if ((e.KeyChar != '1') &&
(e.KeyChar != '2') &&
(e.KeyChar != '3') &&
(e.KeyChar != (Keys.Back))) {
e.Handled = true;
}
}
...但是"e".不会像示例所示那样显示"KeyCode"值,并尝试使用Keys.Back来骂我,运算符'!='无法应用于类型为'char'和'System.Windows.Forms.Keys'的操作数"
...but "e." does not show a "KeyCode" value like the example shows, and trying KeyChar with Keys.Back scolds me with, "Operator '!=' cannot be applied to operands of type 'char' and 'System.Windows.Forms.Keys'"
那我该怎么做呢?
推荐答案
尝试比较e.KeyChar != (char)Keys.Back
,由于Keys是枚举,因此应将其强制转换为char
try comparing e.KeyChar != (char)Keys.Back
, you should cast it to char since Keys is an enumeration
请参见: KeyPressEventArgs. KeyChar
这篇关于如何确定是否在KeyPress事件中按下了Backspace?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!