Search code examples
c#formswinformsmessagebox

Windows forms lost focus when two consecutive MessageBox pop are fired


Class MainForm:Form {
    Public CheckValidation()
    {
    var controller = new FormController();
    controller.checkValidation();
    }
}

    class FormController {
    public checkValidation ()
{
    MessageBox.Show('test_a',MessageBoxButtons.OK, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
    MessageBox.Show('test_b',MessageBoxButtons.OK, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
    }
}

The problem is that after the first message box pop-up box closes, the focus is lost to some other application on windows such as outlook.

The expectation is that the focus is sent to the second message box pop up, which is queued to be executed next. So that I don't have to manually click on the second pop-up box to make it active to close it. And after the second pop-up box closes the focus return to the main form.


Solution

  • Solution: Removing the 'MessageBoxOptions.ServiceNotification' parameter worked.

    Alternative Solution 1:

    If we wish to explicitly specify that the message box should always be in the front and top most window, we can specify parameter ((0x40000) which is flag for MB_TOPMOST option.

    MessageBox.Show('test_a', MessageBoxButtons.OK, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000); //Message Box Top Most (MB_TOPMOST) = 0x40000
    

    Alternative Solution 2: Another way to explicitly specify that the message box should always be in the front and top most window, we can create a new form object and set the ‘TopMost’ Boolean option to ‘True’.

    MessageBox.Show(new Form() { TopMost = true }, 'test_b', MessageBoxButtons.OK, MessageBoxDefaultButton.Button1);