有没有办法在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
textBox1
与Visible
属性设置为false
msg_FormLoad()
中添加以下代码:
txtBox1.Focus();buton1_Click
:
this.Close();P.S:没有测试,因为目前缺乏IDE,但我想它可以调整到很少工作