0
votes

I am showing a message box if a user taps "back" at the main page of a game application.

The usual solution

MessageBoxResult res = MessageBox.Show(txt, cap, MessageBoxButton.OKCancel);
    if (res == MessageBoxResult.OK)
    {
        e.Cancel = false;
        return;
    }

doesn't work for me, because I need those buttons to be localized not with a phone's localization but using app's selected language (i.e. if user's phone has english locale and he has set an app's language to be french, the buttons should be "Oui" and "Non" instead of default "OK" and "Cancel").

I have tried the following approach and it works visually:

protected override void OnBackKeyPress(CancelEventArgs e)
{
    //some conditions
    e.Cancel = true;
    string quitText = DeviceWrapper.Localize("QUIT_TEXT");
    string quitCaption = DeviceWrapper.Localize("QUIT_CAPTION");
    string quitOk = DeviceWrapper.Localize("DISMISS");
    string quitCancel = DeviceWrapper.Localize("MESSAGEBOX_CANCEL");
    Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox(
        quitCaption, 
        quitText,
        new List<string> { quitOk, quitCancel }, 
        0, 
        Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.Error,
        asyncResult =>
        {
            int? returned = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(asyncResult);
            if (returned.Value == 0) //first option = OK = quit the game
            {
                e.Cancel = false;
                return;
            }
        }, 
        null);
    //some more features
}

but it doesn't quit an application.

Which approach should I use? I am not to use "Terminate" because it's a fairly big app and it's not good to quit it that way.

1

1 Answers

2
votes

It doesn't quit because BeginShowMessageBox() is asynchronous. It means that call will return immediatly and because you set e.Cancel to true then application won't ever close (when your event handler will be executed calling method ended without quitting).

Just wait user closes the dialog to set e.Cancel to proper value (omitting AsyncCallback parameter). First remove callback:

IAsyncResult asyncResult = Guide.BeginShowMessageBox(
    quitCaption, quitText, new List<string> { quitOk, quitCancel }, 
    0, MessageBoxIcon.Error, null, null);

Then wait for dialog to be closed:

asyncResult.AsyncWaitHandle.WaitOne();

Finally you can check its return value (as you did in your original callback):

int? result = Guide.EndShowMessageBox(asyncResult);
if (result.HasValue && result.Value == 0)
    e.Cancel = false;