I'm trying to create an WPF application with TaskbarIcon, I suppose if I click the icon in the traybar, it will popup a Contextmenu, and if I select "Exit", then it will show a messagebox asking me whether I want to close this app or not.
Here's the problem, the MessageBox show correctly, but it just disappear IMMEDIATELY BEFORE I click ANY button, and I use debugger to check the "Result" value, I found it's always "No". Does any encounter this problem before? Any single clue would be appreciated!!
Here's my .xaml code:
<tb:TaskbarIcon x:Name="WpfTaskIcon" IconSource="/Themes/Images/TimeSync.ico"
ToolTipText="Hello world" >
<tb:TaskbarIcon.ContextMenu>
<ContextMenu Background="LightCoral">
<MenuItem Header="Exit" Click="Exit_Click" />
<MenuItem Header="Second menu Item" />
</ContextMenu>
</tb:TaskbarIcon.ContextMenu>
and Here's my c# code:
private void Exit_Click(object sender, RoutedEventArgs e)
{
MessageBoxResult result = System.Windows.MessageBox.Show(
"Message_ConfirmationOfExit",
"Title_Confirmation",
MessageBoxButton.YesNo);
if (result == MessageBoxResult.Yes)
{
this.Close();
}
}
edt : I've add this to initialize the visibility of MainWindow :
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
this.Visibility = System.Windows.Visibility.Visible;
MessageBox.Show("MainWindow loaded");
MessageBoxResult result = System.Windows.MessageBox.Show(
"Message_ConfirmationOfExit",
"Title_Confirmation",
MessageBoxButton.YesNo);
if (result == MessageBoxResult.Yes)
{
this.Close();
}
}
I was encountering this problem in other WPF scenarios and the cause was that there was no main UI thread launched yet. If you call MessageBox()
or MsgBox()
or VB InputBox()
without main UI thread launched (=before first form of application is loaded), expected dialog box opens, but vanishes within a second. However, it creates missing UI thread by itself (I suppose... I did not check all the details) because on repeated calls of the same code the message box won't vanish any more.
The solution was to let the first form initialize (typically the main form) before opening of any message box. Invisible initialization counts, too.
Checklist question:
A workaround (not nice but works): if you do not have time for greater changes of the app, store current time before you display your first message box and if you get the reply back within 1500 ms, do not act upon its result (it was not from the user anyway) but re-display the message box again.