ページ

Tuesday, June 12, 2012

Replacement of MessageBox by MessageDialog on Metro Style Application for Windows8

I was wondering how to show a MessageBox and then close an application after clicking "OK" or "Close" button on the MessageBox. Well, it seems we must use MessageDialog instead of MessageBox though.

So, as an example, I will show an implementation in C# about the application requires Internet Connection. ( Just in case network is not available when the application is about to be started. )


1. Add "Using directives" in App.xaml.cs

using System.Net.NetworkInformation;
using Windows.UI.Popups;


2. Add a new method in App.xaml.cs

        private async void MessageBox(string txt, UICommand cmd)
        {
            var md = new MessageDialog(txt);
            md.Commands.Add(cmd);
            await md.ShowAsync();
        }


3. Custome the method "OnLaunched" in App.xaml.cs

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                  UICommand cmd = new UICommand("Close", (p) => { this.Exit(); });
                  MessageBox("Network is not available。", cmd);
            }

            // Do not repeat app initialization when already running, just ensure that
            // the window is active
            if (args.PreviousExecutionState == ApplicationExecutionState.Running)
            {
                  Window.Current.Activate();
                  return;
            }
            .........
        }


I think there must be better solution than this.
So I need to check out more informations about windows8...


No comments:

Post a Comment