WPF的MessageBox不等待结果[WPF的NotifyIcon]结果、WPF、MessageBox、NotifyIcon

2023-09-04 13:06:57 作者:蔓语思

我使用 WPF的NotifyIcon 创建一个系统托盘的服务。当我告诉一个消息,它显示了半秒,然后立即消失,而无需等待输入。

I am using WPF NotifyIcon to create a System Tray service. When I show a messagebox, it shows up for half a second and then disappears immediately without waiting for input.

这种情况有happened前和通常的建议是使用的接受窗口参数的重载。然而,作为一个系统托盘的服务,有没有窗口作为家长使用,而不接受它的位置。

This kind of situation has happened before, and the usual advice is to use an overload which accepts a Window parameter. However, being a System Tray service, there is no window to use as a parent, and null is not accepted in its place.

有没有什么办法,使在MessageBox等待用户输入短创建一个自定义的MessageBox窗口自己的?

Is there any way to make the MessageBox wait for user input short of creating a custom MessageBox window myself?

推荐答案

据答案此处,一个解决方法是实际打开一个不可见的窗口,并使用它作为在MessageBox的父:

According to the answer here, a workaround is to actually open an invisible window and use that as the parent of the 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:

...then open the MessageBox with the appropriate parameter:

        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.