MessageBox没有关注MessageBoxButton
有没有办法在C#中显示MessageBox而不关注消息框中的按钮? 例如,以下代码片段(无法正常工作):
MessageBox.Show("I should not have a button on focus", "Test", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3);
我想要的是显示MessageBox而不关注[是]或[否]。 背景是客户扫描几个在和处有回车的条形码。 因此,当消息框弹出并且他们扫描更多条形码而没有注意到消息框时,他们“按下”按钮。
使用标准MessageBox是不可能的 – 如果你想要这个function,你需要实现自己的。
看到这里是为了让你入门。
那么你可以通过一些技巧来做到这一点。
[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
并且它会使按钮聚焦。 根据我的知识,情况通常如此。 如果您想确保消息框已经显示,您可以使用此代码找到它,然后您可以删除焦点。
- 在项目名称中添加一个新表单
- 在此表单中添加标签,在此标签的文本中写下您的消息
- 添加一个
button1
,其text属性设置为OK
- 添加一个将
Visible
属性设置为false
的textBox1
-
在
msg_FormLoad()
添加此代码:txtBox1.Focus();
-
将此代码添加到
buton1_Click
:this.Close();
-
无论何时您想要显示您的信息,您都可以:
msg msgBox = new msg(); msgBox.ShowDialog();
- 完成了!
PS:没有经过测试,因为目前缺乏IDE,但我猜它可以通过轻松调整工作