c# - 显示 MessageBox 取消 SupressKeyPress=true

标签 c# winforms messagebox

我有一个带有多行 TextBox 的表单。当用户想要创建一个新行时,他应该按 Shift+Enter,但是当他只按 Enter 时,应该没有任何反应。所以这是我的代码:

private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == (Keys.Shift | Keys.Enter))
    {
        int pos = textBox1.SelectionStart;
        textBox1.SelectedText = Environment.NewLine;
        textBox1.SelectionStart = pos + 2;
        e.Handled = e.SuppressKeyPress = true;
        return;
    }
    if (e.KeyCode == Keys.Enter)
    {
        e.SuppressKeyPress = true;
    }
}

这非常有效。

当用户只按下 Enter 时,我想显示一个 MessageBox,所以我添加了以下行:

    ...
    if (e.KeyCode == Keys.Enter)
    {
        MessageBox.Show("Hello"); // <-- Here
        e.SuppressKeyPress = true;
    }

问题是现在显示 MessageBox 后,光标向下移动一行,这是我不希望的。

我该如何解决?我尝试更改 MessageBox 和按键抑制之间的顺序,但它似乎不起作用。

最佳答案

我想问题是您正在从原始控件的处理程序创建另一个控件(MessageBox)。可能重置 supresskeypress 标志。

编辑:原因更微妙,我从@Nouman 链接的链接答案中复制@Hans Passant 的评论:

MessageBox is dangerous when used in the wrong spot, same kind of danger as the infamous DoEvents(). It causes re-entrancy problems. It screws up your SuppressKeyPress request since that won't be done until after your event handler completes. Which won't happen until after the message box closes. Since MessageBox dispatches messages, it will dispatch the KeyPress as well so SuppressKeyPress has no effect whatsoever.

我能够在我的 Linux 机器上重现这个问题,使用 Mono 5.20.1 和 Xamarin 的 WinForms 实现。

用状态栏代替 MessageBox 怎么样?如果您可以更改它,那么下面的代码就可以解决问题。如果没有,按照链接的答案,您将找到 BeginInvoke() 形式的解决方案。

public class MainWindowCtrl
{
    public MainWindowCtrl()
    {
        this.view = new MainWindowView();

        this.view.Editor.KeyDown += (sender, e) => this.OnEditorKeyDown( e );
        this.view.FormClosed += (sender, e) => Application.Exit();

        this.view.Show();
    }

    void OnEditorKeyDown(KeyEventArgs e)
    {
        this.view.StatusBar.Text = "Ready";

        if (e.KeyData == Keys.Enter)
        {
            this.view.StatusBar.Text = "Press Shift + Return!!";
            //MessageBox.Show( "Press Shift + Return!!" );
            e.SuppressKeyPress = true;
            return;
        }

        if (e.KeyData == (Keys.Shift | Keys.Enter))
        {
            int pos = this.view.Editor.SelectionStart;

            this.view.Editor.SelectedText = System.Environment.NewLine;
            this.view.Editor.SelectionStart = pos + 2;

            e.Handled = e.SuppressKeyPress = true;
            return;
        }
    }

    MainWindowView view;
}

希望这对您有所帮助。

关于c# - 显示 MessageBox 取消 SupressKeyPress=true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57164566/

相关文章:

c# - 获取实体的属性列表

c# - 如何在 C# 中声明 C++ 指针

C# WinForms : Make panel scrollbar invisible

c# - 获取交错数组的前三个元素

c++ - 销毁 gtkmm 消息对话框?

windows-phone-7 - 如何让消息框在 3 秒后消失?

c# - 如何在 ASP .NET CORE Identity 中通过 SignInManager 登录后获取用户声明?

c# - 多个消息框选项

java - zk中Messagebox.show()如何实现双语?

c# - 即使文件很大,内存也较少的文件下载