MessageBox.Show in App Closing/Deactivated events

2019-03-04 12:35发布

问题:

I have a MessageBox being shown in Application Closing/Deactivated methods in Windows Phone 7/8 application. It is used to warn the user for active timer being disabled because app is closing. The App Closing/Deactivated events are perfect for this, because putting logic in all application pages would be a killer - too many pages and paths for navigation. This works just fine - message box displays OK in WP7.

I also know for breaking changes in the API of WP8. There it is clearly stated that MessageBox.Show in Activated and Launching will cause exception.

The problem is that in WP8 the message box does not get shown on app closing. Code is executed without exception, but no message appears.

P.S. I've asked this on MS WP Dev forum but obviously no one knew.

回答1:

Move the msgBox code from the app closing events and into your main page codebehind. Override the on back key press event and place your code there. This is how it was done on 7.x:

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("Do you want to exit XXXXX?", "Application Closing", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
            {
                // Cancel default navigation
                e.Cancel = true;
            }
        }

FYI - On WP8 it looks like you have to dispatch the MsgBox Show to a new thread.

This prompts the user before the app ever actually starts to close in the event model. If the user accepts the back key press is allowed to happen, otherwise its canceled. You are not allowed to override the home button press, it must always go immediately to the home screen. You should look into background agents to persist your timer code through suspend / resume.



回答2:

Register BackKeyPress event on RootFrame.

RootFrame.BackKeyPress += BackKeyPressed;
private void BackKeyPressed(object sender, CancelEventArgs e)
    {
        var result = (MessageBox.Show("Do you want to exit XXXXX?", "Application Closing", MessageBoxButton.OKCancel));
        if (result == MessageBoxResult.Cancel)
        {
            // Cancel default navigation
            e.Cancel = true;
        }
}