【问题标题】:Acting only on text input in a KeyPress Event仅作用于 KeyPress 事件中的文本输入
【发布时间】:2010-10-11 09:15:25
【问题描述】:

我有一个按键事件,如果输入不是文本,我希望组合框处理按键。 IE。如果是向上或向下键,让组合框像往常一样处理它,但如果是标点符号或字母数字,我想对其进行操作。

我认为 Char.IsControl(e.KeyChar)) 可以解决问题,但它不能捕捉箭头键,对于组合框来说,这很重要。

【问题讨论】:

    标签: c# winforms char keypress


    【解决方案1】:

    这是我之前给出的答案中的一个示例。它来自 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;
        }
    }
    

    【讨论】:

    • @Malfist:这是一个很好的问题,我个人不知道。我能想象到您对国际字符所做的唯一另一件事是在那里执行另一次检查,这将允许或禁止您感兴趣的 ASCII/Unicode 值。
    【解决方案2】:

    您无需检查任何文本字符。

    我希望下面的代码有帮助:

    void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if(Char.IsNumber(e.KeyChar))
            ...
        else if(Char.IsLetter(e.KeyChar))
            ...
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-18
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多