【问题标题】:Does the KeyDown KeySuppress cancel KeyUp event?KeyDown KeySuppress 是否取消 KeyUp 事件?
【发布时间】:2013-03-14 10:28:50
【问题描述】:

假设我有这个:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 谢谢。这回答了它。
    猜你喜欢
    • 2014-06-12
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    相关资源
    最近更新 更多