Reputation: 449
Is there a way to show an MessageBox in C# without a focus on a button in the message box? For example the following code snippet (which is not working as wished):
MessageBox.Show("I should not have a button on focus",
"Test",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button3);
What i want is that the MessageBox is shown without a focus on [Yes] or [No]. Background is that the customer scans several barcodes which have an carriage return at the and. So when the messagebox pops up and they scan further barcodes without noticing the message box they "press" a button.
Upvotes: 7
Views: 9895
Reputation: 73502
Well you can do it certainly with some trick.
[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);
}
Note that the above code assumes that when BeginInvoke
is called MessageBox
is shown and it got the button focused. It will be the case usually upto my knowledge. If you want to make sure message box has shown already you can use this code to find it and then you can remove the focus.
Upvotes: 9
Reputation: 2817
msg
button1
with its text property set to OK
textBox1
with the Visible
property set to false
add this code in msg_FormLoad()
:
txtBox1.Focus();
add this code to buton1_Click
:
this.Close();
whenever you want to show your message you can just:
msg msgBox = new msg(); msgBox.ShowDialog();
P.S: not tested because the lack of IDE for the moment but I guess it can be adjusted to work with little effort
Upvotes: 0
Reputation: 5445
This isn't possible with the standard MessageBox - you'll need to implement your own if you want this functionality.
See here to get you started.
Upvotes: 4