MessageBox没有关注MessageBoxButton

问题描述 投票:7回答:3

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

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

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

c# .net
3个回答
4
投票

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

请参阅here以帮助您入门。


9
投票

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

[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找到它,然后您可以删除焦点。


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

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

© www.soinside.com 2019 - 2024. All rights reserved.