简体   繁体   English

WPF MessageBox不等待结果[WPF NotifyIcon]

[英]WPF MessageBox not waiting for result [WPF NotifyIcon]

I am using WPF NotifyIcon to create a System Tray service. 我正在使用WPF NotifyIcon来创建系统托盘服务。 When I show a messagebox, it shows up for half a second and then disappears immediately without waiting for input. 当我显示一个消息框时,它会显示半秒钟然后立即消失而不等待输入。

This kind of situation has happened before , and the usual advice is to use an overload which accepts a Window parameter. 之前发生过这种情况,通常的建议是使用一个接受Window参数的重载。 However, being a System Tray service, there is no window to use as a parent, and null is not accepted in its place. 但是,作为系统托盘服务,没有窗口可用作父级,并且不接受null

Is there any way to make the MessageBox wait for user input short of creating a custom MessageBox window myself? 有没有办法让MessageBox等待用户输入自己创建一个自定义MessageBox窗口?

You don't need to create a proxy window for this. 您无需为此创建代理窗口。 Just add MessageBoxOptions.DefaultDesktopOnly to your message box and it will fire on your desktop without disappearing. 只需将MessageBoxOptions.DefaultDesktopOnly添加到您的消息框中,它就会在您的桌面上触发而不会消失。

Example

MessageBox.Show("My Message", "Title", MessageBoxButton.OK, 
    MessageBoxImage.Information, MessageBoxResult.OK, 
    MessageBoxOptions.DefaultDesktopOnly);

According to the answer here , a workaround is to actually open an invisible window and use that as the parent of the MessageBox: 根据这里的答案,一个解决方法是实际打开一个不可见的窗口并将其用作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();

...then open the MessageBox with the appropriate parameter: ...然后使用适当的参数打开MessageBox:

        MessageBox.Show(window, "Titie", "Text");

...and don't forget to close the window when you're done (possibly on application exit): ...当你完成时(可能在应用程序退出时)不要忘记关闭窗口:

        window.close();

I tried this and it works well. 我试过这个并且效果很好。 It's undesirable to have to open an extra window, but it's better than making your own messagebox window just for the sake of making this work. 不得不打开一个额外的窗口是不可取的,但它比制作你自己的消息框窗口更好,只是为了让这个工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM