强制 MessageBox 位于 .net/WPF 中的应用程序窗口顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10092564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force MessageBox to be on top of application window in .net/WPF
提问by Tom Davies
In my WPF app, I sometimes being up a System.Windows.MessageBox
. When it is initially displayed, it is shown on top of my main application window, as I would like. Is there a way that I can force it to ALWAYS remain top of the main window? The problem I have is that when a MessageBox
is displayed, users can then click on the main app window and bring it to the front, meaning the MessageBox
becomes hidden from view. In this case the user might not realize it's there, or forget about it, and to them, the main app seems to have frozen.
在我的 WPF 应用程序中,我有时会启动一个System.Windows.MessageBox
. 当它最初显示时,它会显示在我的主应用程序窗口的顶部,正如我所希望的。有没有办法可以强制它始终保持在主窗口的顶部?我遇到的问题是,当MessageBox
显示a 时,用户可以单击主应用程序窗口并将其置于最前面,这意味着MessageBox
隐藏在视图中。在这种情况下,用户可能没有意识到它的存在,或者忘记了它,对他们来说,主应用程序似乎已经冻结。
I've read a number of threads about this, but none have resolved the problem for me.
我已经阅读了许多关于此的主题,但没有一个为我解决了问题。
I ought to add that the thread putting up the MessageBox
might not be the UI thread.
Thanks
Tom
我应该补充一点,线程MessageBox
可能不是 UI 线程。谢谢汤姆
回答by Ricibob
Use the version of MessageBox.Show
that takes a Window "owner" and pass your window.
使用MessageBox.Show
需要窗口“所有者”的版本并传递您的窗口。
MessageBox.Show(Application.Current.MainWindow, "Im always on top - of the main window");
If your possibly not on the UI thread try:
如果您可能不在 UI 线程上,请尝试:
string msg="Hello!";
if (Application.Current.Dispatcher.CheckAccess()) {
MessageBox.Show(Application.Current.MainWindow, msg);
}
else {
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(()=>{
MessageBox.Show(Application.Current.MainWindow, msg);
}));
}
You can:
1. Invoke
to block your thread until MessageBox
is dismissed OR
2. BeginInvoke
in which case your thread code will continue to execute but UI thread will block on MessageBox
until its dismissed).
您可以:
1.Invoke
阻塞您的线程直到MessageBox
被解散或
2.BeginInvoke
在这种情况下,您的线程代码将继续执行,但 UI 线程将阻塞MessageBox
直到它被解散)。
回答by juni-j
This is a quick way of putting the Message Box on top of the application windows.
这是将消息框放在应用程序窗口顶部的一种快捷方式。
MessageBox.Show(this ,"Output text"));
MessageBox.Show(this ,"Output text"));
回答by GMG
Inside your "public partial class MainWindow : Window
" place the following code. So the Invoke will run your code inside UI thread.
在您的“ public partial class MainWindow : Window
”中放置以下代码。因此 Invoke 将在 UI 线程中运行您的代码。
void ShowErrorMessage(ERROR err)
{
this.Dispatcher.Invoke((Action)(() =>
{
MessageBox.Show(err.description, err.code.ToString(), MessageBoxButton.OK, MessageBoxImage.Error);
}));
}