Search code examples
c#winformsformsvisual-studiomessagebox

Form hides behind the other form after ShowDialog()


I have used a customized Messagebox in my application that inherits from the Form class. It works fine when I use it on my main form. But when I use its Show() function on a form that is itself popped up from the main form, the Messagebox hides under the second form and the program therefore becomes unavailable.

Even when I use its BringToFront() function before ShowDialog() it still goes back. This is the Show() function of this customized Messagebox. I can share more of its code if necessary:

public static DialogResult Show(string message, string title)
{
    _msgBox = new MsgBox();
    _msgBox._lblMessage.Text = message;
    _msgBox._lblTitle.Text = title;
    _msgBox.Size = MsgBox.MessageSize(message);

    MsgBox.InitButtons(Buttons.OK);
    //_msgBox.BringToFront();
    _msgBox.ShowDialog();
    return _buttonResult;
}

MsgBox is the name of the class itself:

class MsgBox : Form

Solution

  • Try to pass the Owner value for your internal message box class

    public static DialogResult Show(string message, string title, Form owner = null)
    {
        _msgBox = new MsgBox();
        _msgBox._lblMessage.Text = message;
        _msgBox._lblTitle.Text = title;
        _msgBox.Size = MsgBox.MessageSize(message);
    
        MsgBox.InitButtons(Buttons.OK);
        if(owner != null)
            _msgBox.ShowDialog(owner);
        else
            _msgBox.ShowDialog();
        return _buttonResult;
    }
    

    Using a default parameter you could change the code only where is needed.

    After a little research I have found this question and its answers that explains a bit this behavior