Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MessageBox without focus on a MessageBoxButton

Tags:

c#

.net

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.

like image 550
Daniel W. Avatar asked Feb 20 '15 08:02

Daniel W.


2 Answers

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.

like image 63
Sriram Sakthivel Avatar answered Nov 02 '22 04:11

Sriram Sakthivel


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.

like image 4
RagtimeWilly Avatar answered Nov 02 '22 04:11

RagtimeWilly