System.Windows.MessageBox doesn't wait for use

2019-02-16 06:25发布

...and it makes no sense why. T-T

In my Application_Startup event handler I have code that looks kinda like this:

private void Application_Startup(object sender, StartupEventArgs e)
{
    string errorMessage;

    if(CheckStartUpConditions(out errorMessage))
    {
        (new MainWindow()).Show();
    }
    else
    {
        MessageBox.Show(errorMessage, "Application Startup", 
            MessageBoxButton.OK, MessageBoxImage.Error);

        Shutdown();
    }
}

private bool CheckStartUpConditions(out string errorMessage)
{
    errorMessage = string.Empty;  

    if(...)
        errorMessage += "Please login to xxx. ";

    if(...)
        errorMessage += "Please install xxx.";

    if(string.IsNullOrEmpty(errorMessage))
        return true;
    else
        return false;
}

The message box makes an brief appearance for like a second before going "POOF!" It doesn't wait for me to click "OK" or on the "X" button. I'm really stumped as to why this is occuring, so any help would be greatly appreciated.

I've tried commenting out the call to Shutdown just for kicks and giggles, and it still behaves the same way.

Also, the application also has a SplashScreen, so I don't know if that's effecting this.

EDIT: I added more code if that helps. The message box is showing the correct error message. Just won't stay long enough for the users to read it. >:(

EDIT PART 2: Okay...I think I've found the culprit. :( I changed the build action on the image I'm using as my splash from SplashScreen to None and the message box will now stay and wait for user input. I don't understand why the SplashScreen is screwing with the MessageBox. >:(

7条回答
ゆ 、 Hurt°
2楼-- · 2019-02-16 07:28

Alexey is right, the splash screen closes the message box.

A simple way to avoid this is to use the native MessageBox function:

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);

public static void Main()
{
   ...
   MessageBox(new IntPtr(0), "Hello World!", "MyApp", 0);
查看更多
登录 后发表回答