我有一个按键事件,如果输入不是文本的话,我希望组合框能够处理按键。 I.E.如果它是向上或向下键,让组合框像通常那样处理它,但如果它是标点符号或字母数字,我想对它采取行动。
我认为 Char.IsControl(e.KeyChar))可以做到这一点,但是它没有抓住箭头键,对于组合框,这很重要。
答案 0 :(得分:2)
这是我之前给出的答案中的一个例子。它来自MSDN文档,我认为你应该能够根据你想要或不允许的字符很好地修改它:
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if(e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
//If shift key was pressed, it's not a number.
if (Control.ModifierKeys == Keys.Shift) {
nonNumberEntered = true;
}
}
// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
if (nonNumberEntered == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
}
}
答案 1 :(得分:0)
您无需检查任何文字字符。
我希望以下代码有所帮助:
void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
if(Char.IsNumber(e.KeyChar))
...
else if(Char.IsLetter(e.KeyChar))
...
}