Frage

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.

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.

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

War es hilfreich?

Lösung 2

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();

...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.

Andere Tipps

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.

Example

MessageBox.Show("My Message", "Title", MessageBoxButton.OK, 
    MessageBoxImage.Information, MessageBoxResult.OK, 
    MessageBoxOptions.DefaultDesktopOnly);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top