MessageBox没有关注MessageBoxButton

时间:2015-02-20 08:08:57

标签: c# .net

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

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

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

3 个答案:

答案 0 :(得分: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找到它,然后您可以删除焦点。

答案 1 :(得分:4)

使用标准MessageBox无法做到这一点 - 如果您需要此功能,则需要实现自己的功能。

请参阅here以帮助您入门。

答案 2 :(得分:0)

  • 将新表单添加到项目名称msg
  • 在此表单中添加标签,在此标签的文字中写下您的信息
  • 添加button1,其文字属性设置为OK
  • 添加textBox1Visible属性设置为false
  • msg_FormLoad()

    中添加此代码

    txtBox1.Focus();

  • 将此代码添加到buton1_Click

    this.Close();

  • 每当您想要显示信息时,您都可以:

    msg msgBox = new msg(); msgBox.ShowDialog();

  • 完成!
P.S:没有经过测试,因为目前缺乏IDE,但我猜它可以调整到很少工作

相关问题