[WPF] twenty-sixth chapter of the Application class learning - the life cycle of the application

Original: [WPF] twenty-sixth chapter of the Application class learning - life cycle of the application

  In WPF, the application will undergo a simple life cycle. After the application starts, will immediately create an application objects, triggering a variety of applications in the event the application is running, you can choose to monitor some of these events. Finally, when the release of the application object, the application will end.

First, create the Application object

  The easiest way to use the Application class is to manually create it. The following example shows a minimal program: create a window named MainWindow in the application entry (Main () method) at, and start a new application:

  In essence, the same model as the Visual Studio Application class model used for the window. XAML starting point is a template that is named App.xaml By default, it looks like this:

<Application x:Class="TestApplication.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
</Application>

  In the " [WPF] Chapter IV study load and compile XAML " introduced, to create a class derived from the use of Class attribute elements in XAML. Therefore, the class is derived from the creation of the Application class, class named TestApplication.App (TestApplication is the project name, which is also in the class namespace definition, App is Visual Studio Application name is derived from a custom class. If you prefer , the class name can be any more interesting content).

  Application label not only create a custom application class, also set the property to determine StartupUri XAML document on behalf of the main window. Thus, no time code is displayed with the window --XAML instantiate the parser this automatically.

  Like the windows, the application classes are defined in two separate portions, fused together at compile time. Automatically generating part is not visible in the project, but the portion comprising Main () an inlet to launch the application code. This section looks like this:

Copy the code
public class App:Application
    {
        [STAThread]
        public  static  void Main ()
        {
            Program app = new Program();
            app.MainWindow = new MainWindow("MainWindow.xaml");
            app.MainWindow.ShowDialog();
        }
    }
Copy the code

  If you really interested in seeing a custom application class XAMl template created, can be found located obj \ App.g.cs file in the project directory Debug folder.

  The only distinction between the custom application class code written manually and automatically generated code is given here, automatically generated classes and attributes StartupUri, instead of setting MainWindow property or form are following as a parameter passed to Run () method. Just use the same URI format, free to create a custom application class using this method. You need to create an object relative Uri for XAML document (the XAML document is a translation of the name of the project, as BAML resources are embedded in the application of the assembly. The name of the resource is the name of the original XAML file. Above example, the application contains a resource named MainWindow.xaml of the resource contains the compiled XAML document).

  From the second section defines the application class files stored in the project, such as the App.xaml.cs. This section contains the code to handle events developers to add, initially empty:

public partial class App : Application
    {
    }

  This document by partially fused together and automatic class generation application code.

Third, how the application is closed

  In general, as long as there has not yet closed the window, Application class to keep the application active. If this is not the desired behavior, adjustable Application.ShutdownMode property. If the Application object instantiates manually, you need to set ShutdownMode property before calling Run () method. If you use App.xaml file, simply set ShutdownMode property in XAML file.

  There are three options for the shutdown mode, as shown in the following table:

ShutdownMode enumeration value table

   For example, if you want to use OnMainWindowClose way, and are using App.xaml file, you need to add the following:

<Application x:Class="TestApplication.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml" ShutdownMode="OnMainWindowClose">
</Application>

  Regardless of the closed method you choose, you can always use Application.Shutdown () method immediately terminate the application (of course, when you call Shutdown () method, the application may not immediately stop running. Call Application.Shutdown () method causes Application. run () method returns immediately, but can continue to run with the other codes Main () method or in response to events Application.Exit).

Fourth, the application event

  Initially, App.xaml.cs file does not contain any code. Although no code, but you can add code to handle application events. Application class provides a few very useful event. The following table shows the importance of a few of them.

Table Application Event

    There are two options when dealing with events: the associated event handler or rewrite the protected method. If you choose to handle application events, without the use of delegate code to associate the event handler, but you can use a feature App.xaml file to associate the event handler. For example, if you have an event handler:

Copy the code
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show("An unhandled " + e.Exception.GetType().ToString() +
                " exception was caught and ignored.");
            e.Handled = true;
        }
Copy the code

  XAML can be used to connect the above following event handlers:

Copy the code
<Application x:Class="TestApplication.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml" ShutdownMode="OnMainWindowClose" DispatcherUnhandledException="Application_DispatcherUnhandledException">
    <Application.Resources>
         
    </Application.Resources>
</Application>
Copy the code

  For each application event, you can call the appropriate method to raise the event. The name of this method is the name of the event, just in front of the prefix On, therefore Startup became OnStartup (), Exit become OnExit (), and so on. This way in .NET is very common. The only exception is DispatcherExceptionUnhandled event - the event is no corresponding OnDispatcherExceptionUnhandled () method, so always need to use the event handler.

  The following is a custom application class, which overrides the OnSessionEnding () method, and if not set the appropriate flag, which prevents shut down the system and the application itself:

Copy the code
public partial class App : Application
    {

        private bool unsavedData = false;
        public bool UnSavedData
        {
            get { return unsavedData; }
            set { unsavedData = value; }
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            unsavedData = true;
        }

        protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
        {
            base.OnSessionEnding(e);
            if (unsavedData)
            {
                e.Cancel = true;
                MessageBox.Show(
                    "The application attempted to be closed as a result of " +
                    e.ReasonSessionEnding.ToString() +
                    ".This is not allowed,as you have unsaved data.");
            }
        }
}
Copy the code

  When rewriting the application method, the base class implementation preferably first call. Typically, to achieve knowledge base classes lead to a corresponding application event.

  Clearly, a more sophisticated way to achieve this technology is not used the message box, but should show some confirmation dialog box that lets the user choose to continue (to exit the application and Window System) or cancel the shutdown.

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12285977.html