Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Message box closes automatically after a brief delay

Tags:

c#

wpf

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

like image 522
Redaa Avatar asked Jul 31 '14 17:07

Redaa


1 Answers

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

like image 155
Nathan A Avatar answered Sep 20 '22 03:09

Nathan A