WPF MessageBox does not wait for result [WPF NotifyIcon]

I am using WPF NotifyIcon to create a system tray service. When I show a message, it appears for half a second, and then immediately disappears, without waiting for input.

This situation happened before , and the usual advice is to use an overload that accepts the Window parameter. However, as a system tray service, there is no window to use as a parent, and null not accepted in its place.

Is there a way to make MessageBox wait for user input without creating its own MessageBox window?

+6
source share
2 answers

According to the answer here , a workaround is to actually open an invisible window and use it as the parent of a 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 do not forget to close the window when done (possibly when the application exits):

  window.close(); 

I tried this and it works well. It is undesirable to open an additional window, but this is better than creating your own message window only for the sake of doing this work.

0
source

You do not need to create a proxy window for this. Just add MessageBoxOptions.DefaultDesktopOnly to the 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); 
+14
source

All Articles