MessageBox没有关注MessageBoxButton

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MessageBox没有关注MessageBoxButton相关的知识,希望对你有一定的参考价值。

有没有办法在C#中显示MessageBox而不关注消息框中的按钮?例如,以下代码片段(无法正常工作):

 MessageBox.Show("I should not have a button on focus",
                        "Test",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button3);

我想要的是显示MessageBox而不关注[是]或[否]。背景是客户扫描几个在和处有回车的条形码。因此,当消息框弹出并且他们扫描更多条形码而没有注意到消息框时,他们“按下”按钮。

答案

使用标准MessageBox是不可能的 - 如果你想要这个功能,你需要实现自己的。

请参阅here以帮助您入门。

另一答案

那么你可以通过一些技巧来做到这一点。

[DllImport("user32.dll")]
static extern IntPtr SetFocus(IntPtr hWnd);

private void button1_Click(object sender, EventArgs e)

    //Post a message to the message queue.
    // On arrival remove the focus of any focused window. 
    //In our case it will be default button.
    this.BeginInvoke(new MethodInvoker(() =>
    
        SetFocus(IntPtr.Zero);//Remove the focus
    ));

    MessageBox.Show("I should not have a button on focus",
               "Test",
               MessageBoxButtons.YesNo,
               MessageBoxIcon.Question,
               MessageBoxDefaultButton.Button3);

请注意,上面的代码假设当BeginInvoke被调用时,会显示MessageBox,并且按钮会聚焦。根据我的知识,情况通常如此。如果您想确保消息框已经显示,您可以使用this code找到它,然后您可以删除焦点。

另一答案
  • 将新表单添加到项目名称msg
  • 在此表单中添加标签,在此标签的文本中写下您的消息
  • 添加一个button1,其text属性设置为OK
  • 添加一个textBox1Visible属性设置为false
  • msg_FormLoad()中添加以下代码: txtBox1.Focus();
  • 将此代码添加到buton1_Click: this.Close();
  • 无论何时您想要显示您的信息,您都可以: msg msgBox = new msg(); msgBox.ShowDialog();
  • 完成了!

P.S:没有测试,因为目前缺乏IDE,但我想它可以调整到很少工作

以上是关于MessageBox没有关注MessageBoxButton的主要内容,如果未能解决你的问题,请参考以下文章

我的vs2008 不能直接用 messagebox.show

C语言中messagebox的用法

asp.net 怎么把messagebox显示在页面之前

为 Windows 11 更新 Application.Messagebox 的外观

MessageBox 函数

在WPF中MessageBox的显示如何定义其参数