c# - KeyDown KeySuppress 是否取消 KeyUp 事件?

标签 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 键?

最佳答案

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

        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");
            }
        }

关于c# - KeyDown KeySuppress 是否取消 KeyUp 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15406691/

相关文章:

c# - WPF 中的菜单项被切断

c# - Fluent API 首先在 EF Code 中实现零或一到零或一的关系

c# - 让 FluentValidation 调用具有多个参数的函数

c# - DataGridView-当我按下回车键时,它会转到下一个单元格

c# - 调试 Windows 窗体应用程序

c# - 从任务更新一个 int 变量?

c# - 在多个 select 语句上运行参数化查询

c# - 如何从一个用户控件调用另一个用户控件的方法?

.net - 如何提高垃圾收集性能?

c# - 在 .NET 3.5 中使用 URI 类时保持 url 编码