KeyDown KeySuppress是否取消KeyUp事件?

时间:2013-03-14 10:28:51

标签: c# .net winforms events keyboard-events

让我说我得到了这个:

    private void txtAnalogValue_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            //Non-numeric key pressed => prevent this from being input into the Textbox
            e.SuppressKeyPress = true;
        }
    }

和此:

    private void txtAnalogValue_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            try
            {
                UpdateState(double.Parse(((TextBox)sender).Text));
            }
            catch (Exception ex)
            {
                ((TextBox)sender).Text = ioElement.StateVal.ToString("0.00");
            }
        }
    }

我知道这段代码没有多大意义,它只是测试。 问题是:KeyDown事件中的e.SuppressKeyPress = true会对KeyUp事件产生影响,因此不会接受Enter键吗?

1 个答案:

答案 0 :(得分:2)

不,e.SuppressKeyPress = true将忽略Enter键(它不会转到下一行,文本框的Text属性也不会更改),e.Keycode将在KeyUp。因此,取消KeyDown中的密钥不会影响KeyUp事件,您的代码应该可以正常工作。当您点击UpdateState中的Enter按钮时,系统会调用TextBox。您可以尝试使用此代码进行检查:

        private void txtAnalogValue_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.A)
            {
                e.SuppressKeyPress = true;
            }
        }

        private void txtAnalogValue_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.A)
            {
                MessageBox.Show("Up");
            }
        }