MessageBox without focus on a MessageBoxButton

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.


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.

Tags:

C#

.Net