我正在使用WPF NotifyIcon创建一个系统托盘服务。当我显示一个消息框时,它会显示半秒,然后立即消失,而不需要等待输入。
这种情况以前发生过,通常的建议是使用接受Window
参数的重载。然而,作为一个系统托盘服务,没有窗口可以用作父窗口,并且null
不被接受。
是否有任何方法可以使MessageBox等待用户输入,而无需自己创建自定义MessageBox窗口?
您不需要为此创建代理窗口。只需添加MessageBoxOptions。DefaultDesktopOnly到你的消息框,它会在你的桌面上启动而不消失。
例子MessageBox.Show("My Message", "Title", MessageBoxButton.OK,
MessageBoxImage.Information, MessageBoxResult.OK,
MessageBoxOptions.DefaultDesktopOnly);
根据这里的答案,一个解决方法是实际打开一个不可见的窗口,并将其用作MessageBox的父窗口:
Window window = new Window()
{
Visibility = Visibility.Hidden,
// Just hiding the window is not sufficient, as it still temporarily pops up the first time. Therefore, make it transparent.
AllowsTransparency = true,
Background = System.Windows.Media.Brushes.Transparent,
WindowStyle = WindowStyle.None,
ShowInTaskbar = false
};
window.Show();
…然后用适当的参数打开MessageBox:
MessageBox.Show(window, "Titie", "Text");
…当你完成时不要忘记关闭窗口(可能在应用程序退出时):
window.close();
我试过了,效果很好。打开一个额外的窗口是不可取的,但这比仅仅为了使它工作而创建自己的消息框窗口要好。