代码改变世界

keypress事件

2011-08-19 17:59  墨泣  阅读(620)  评论(0编辑  收藏  举报

 

在控件有焦点的情况下按下键时发生。

键事件按下列顺序发生:

  1. KeyDown

  2. KeyPress

  3. KeyUp

非字符键不会引发 KeyPress 事件;但非字符键却可以引发 KeyDownKeyUp 事件。

使用 KeyChar 属性在运行时对键击进行取样,并且使用或修改公共键击的子集。

若要仅在窗体级别处理键盘事件而不允许其他控件接收键盘事件,请将窗体的 KeyPress 事件处理方法中的 KeyPressEventArgs.Handled 属性设置为 true

有关处理事件的更多信息,请参见 使用事件

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

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