简体   繁体   中英

Message box closes automatically after a brief delay

i have a wpf application, i need to display a messagebox, the problem is that the message box is displayed for 0.5 second and doesn't even wait for user to click OK.

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    public MainWindow()
    {

        //verifying application setting file to see if the connection is ok
        string pathToApp = System.AppDomain.CurrentDomain.BaseDirectory + "settings.sts";
        ApplicationSettings applicationSettings = new ApplicationSettings();
        applicationSettings.ServerIp = "127.0.0.1";
        applicationSettings.ServerDatabase = "test";
        applicationSettings.ServerUserName = "root";
        applicationSettings.MakeConnectionString();
        foreach (char  c in "")
        {
            applicationSettings.ServerPassword.AppendChar(c);
        }



        MySqlConnection connection = new MySqlConnection(applicationSettings.ConnectionString);
        try
        {
            connection.Open();
        }
        catch (Exception e)
        {
            // here the message box shows for 0.5 second and closes immediately
            MessageBox.Show(e.Message);
        }
        finally
        {
            connection.Close();
        }

        //display window
        InitializeComponent();

    }

i should also that am using a image as a splash screen, if this have a relation with the message box.

sorry this code is not yet completed. thanks in advance

Your problem stems from a known issue with WPF:

First, it happens when used with the splash screen. If you don't specify an parent for a message box, it assumes the splash screen is it's parent and is therefore closed when the splash screen closes. Second, even if you specify the parent as the MainWindow while in MainWindow's constructor, it still won't work since MainWindow doesn't have a handle yet (it gets created later on).

So, the solution is to postpone the invocation of the message box until after the constructor, and by specifying MainWindow as the parent. Here is the code that fixes it:

Dispatcher.BeginInvoke(
    new Action(() => MessageBox.Show(this, e.Message)),
    DispatcherPriority.ApplicationIdle
);

Here's a reference to the parent/splash issue: http://connect.microsoft.com/VisualStudio/feedback/details/381980/wpf-splashscreen-closes-messagebox

In my situation (minimal tray icon app) there was no splash screen or MainWindow.

I found this solution from another SO question helpful:

var tempWindow = new Window();
var helper = new WindowInteropHelper(tempWindow);
helper.EnsureHandle();
MessageBox.Show(tempWindow, "Lorem Ipsum");
tempWindow.Close();

(I am not sure if the .Close() can be omitted)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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