Search code examples
c#messageboxtopmost

C#, Windows Form, Messagebox on top not working


I've some MessageBox that I code like this:

MessageBox.Show(new Form(){TopMost=true, TopLevel=True}, "Message","Title", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

For a better example, I do this for the FormClosing Event:

private void Example_FormClosing(object sender, FormClosingEventArgs e){
MessageBox.Show(new Form(){TopMost=true, TopLevel=True}, "Really close?"," Program", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}

But, almost every time I've to change of Window on my computer (like return on Visual Studio) before seeing my messagebox and it's not user-friendly and really annoying.

I verified that my principal form was not in TopMost=true, I tried just the TopMost or just the TopLevel,the StartPosition=FormStartPosition.CenterScreen but nothing worked.

[Update]

I tried:

 private void Example_FormClosing(object sender, FormClosingEventArgs e){
    MessageBox.Show(this.Owner, "Really close?"," Program", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
    }

I'd like to have my messageBox on the front of my window and not have to change of window to see it because it's like behind the current window.

Have you an idea to resolve this problem?


Solution

  • Given an instance of your Form, you can call a MessageBox like this:
    MessageBox.show(form, "Message", "Title"); (Check the doc for other parameters.)

    However if you want to call this from a background thread (e.g.: BackgroundWorker) you have to use Form.Invoke() like this:

    form.Invoke((MethodInvoker)delegate
    {
       MessageBox.show(form, "Message", "Title");
    });