【问题标题】:MessageBox does not suppress keyboard Enter keyMessageBox 不抑制键盘 Enter 键
【发布时间】:2021-07-08 03:37:49
【问题描述】:

我有一个按钮,在Click 事件中,我对Form 中的一些TextBoxes 进行了一些验证。 如果TextBox 没有通过验证,那么我强制将Focus 输入它(用户必须在TextBox 中输入一些字符)。如果用户按下 Enter 键,我的 TextBox 类已经有一些代码可以转到下一个控件。

MyTextBox.cs 类

public class MyTextBox : TextBox
{
    public MyTextBox(){
        KeyUp += MyTextBox_KeyUp;
        KeyDown += MyTextBox_KeyDown;
    }

    private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            // This will suppress Blink sound
            e.SuppressKeyPress = true;
        }
    }

    private void MyTextBox_KeyUp(object sender, KeyEventArgs e)
    {
        if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
        {
            // This will go to the next control if Enter will be pressed.
            SendKeys.Send("{TAB}");
        }
    }
}

表单的按钮点击事件:

private void BtnPrint_Click(object sender, EventArgs e){
    // txtName is based on MyTextBox class
    if(txtName.Text.Length == 0){
        MessageBox.Show("Name field could not be empty! Please fill the Name!", "Error Message",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
        // If I Click the OK button, txtName will stay focused in the next line,
        // but if I press Enter key, it will go to the next control.
        txtName.Focus();
        return;
    }
    // Some other validations ...
    // Calling printing method ...
}

当用户在 MessageBox 中按 Enter 键时,我如何停止失去对文本框的关注?

【问题讨论】:

    标签: c# winforms messagebox


    【解决方案1】:

    在某些情况下,MessageBox 可能会导致重入问题。这是一个经典的。

    在这种特定情况下,当按下 Enter 键向对话框发送确认消息时,KeyUp 事件重新进入消息循环并被调度到主动控制。文本框,在这里,因为这个调用:txtName.Focus();

    发生这种情况时,TextBox 的KeyUp 事件处理程序中的代码会再次被触发,从而导致SendKeys.Send("{TAB}");

    有不同的方法来解决这个问题。在这种情况下,只需使用TextBox.KeyDown 事件来抑制Enter 键并移动焦点:

    private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            e.SuppressKeyPress = true;
            SendKeys.Send("{TAB}");
        }
    }
    

    另请参阅(例如):

    Pushing Enter in MessageBox triggers control KeyUp Event
    MessageBox causes key handler to ignore SurpressKeyPress

    作为处理类似情况的不同方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-12
      • 2015-07-29
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多