C#,Windows Form,Messagebox在上面不起作用

Ali*_*ice 7 c# messagebox topmost

我有一些MessageBox,我的代码如下:

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

为了更好的示例,我为FormClosing事件执行此操作:

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

但是,几乎每次我都要在我的计算机上更改Window(比如返回Visual Studio),然后才能看到我的消息框,而且这不是用户友好的,而且非常烦人.

我确认我的主要表单不在TopMost = true中,我只尝试了TopMost或只是TopLevel,StartPosition = FormStartPosition.CenterScreen但没有任何效果.

[更新]

我试过了:

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

我想把我的messageBox放在我的窗口前面而不必更改窗口来查看它,因为它就像在当前窗口后面.

你有想法解决这个问题吗?

Mat*_*son 10

像这样做:

MessageBox.Show(
    "Message", 
    "Title", 
    MessageBoxButtons.YesNo, 
    MessageBoxIcon.Warning, 
    MessageBoxDefaultButton.Button1, 
    MessageBoxOptions.DefaultDesktopOnly);
Run Code Online (Sandbox Code Playgroud)

它将把它放在所有其他窗口的前面,包括来自其他进程的窗口(这是我认为你要求的).

关键参数是MessageBoxOptions.DefaultDesktopOnly.请注意,这会将消息框设置为默认桌面,从而导致应用程序调用MessageBox.Show()失去焦点.

(您应该为关键消息保留此行为.)

或者,如果您的应用程序有一个窗口,请this.BringToFront()在显示消息框之前调用,方法是调用MessageBox.Show()并将第一个参数设置为this.(你可以从窗体类中调用它).


Lar*_*ars 5

鉴于你的情况Form,你可以调用一个MessageBox这样的:
MessageBox.show(form, "Message", "Title");。检查是否有其他参数DOC

但是,如果您想从后台线程(例如:)调用它,则BackgroundWorker必须Form.Invoke()像这样使用:

form.Invoke((MethodInvoker)delegate
{
   MessageBox.show(form, "Message", "Title");
});
Run Code Online (Sandbox Code Playgroud)