WPF程序Application的生命周期
WPF程序的生命周期由 Application
类控制。Application
类是WPF程序中的核心类,它负责管理整个应用程序的启动、运行和关闭。理解WPF应用程序的生命周期对于开发高效且可维护的WPF应用非常重要。以下是详细讲解WPF程序中 Application
的生命周期。
1. 启动阶段
WPF应用程序的启动由 App.xaml
文件中的 Application
类控制。App.xaml
文件中定义了应用程序的资源、事件处理程序等。应用程序的启动过程通常分为以下几个阶段:
(1) App.xaml
被加载
在WPF应用程序启动时,App.xaml
文件会被加载。这个文件包含了应用程序的基础配置和资源。在 App.xaml
中,可以定义全局的资源字典、样式、主题等资源。
<Application x:Class="WpfApp1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
</Application>
x:Class
属性指定了Application
类的完全限定名。StartupUri
属性指定了应用程序启动时加载的窗口(例如,MainWindow.xaml
)。
(2) App
类的初始化
App.xaml
会通过自动生成的 App.xaml.cs
类进行初始化。App
类会创建并启动一个 Application
实例。你可以在 App.xaml.cs
中的构造函数或 OnStartup
方法中执行一些初始化逻辑。
public partial class App : Application
{
public App()
{
// 这里可以执行一些初始化操作
}
}
2. 启动阶段(Startup
事件)
在 App.xaml
中指定了 StartupUri
后,应用程序启动时,会触发 Startup
事件。Startup
事件是程序启动的一个重要时刻,通常可以在这个阶段执行一些应用程序级别的初始化代码。
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// 你可以在这里添加应用程序的初始化代码
// 比如,设置主窗口,启动必要的服务等
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
}
}
StartupEventArgs
中包含了启动参数(如果有的话)。- 在
OnStartup
方法中,我们可以做很多事情,比如配置服务、设置主窗口、加载配置文件等。最重要的是,我们在这里通常会创建并显示主窗口。
3. 主窗口的显示
在 OnStartup
方法中,我们可以显式地创建主窗口并显示它。通常,MainWindow.xaml
文件会自动被指定为应用程序的主窗口,但你也可以在代码中手动创建并显示它。
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
Show()
方法用于显示窗口。窗口显示后,用户可以与应用程序进行交互。
4. 运行阶段(Run
方法)
在 OnStartup
方法中,Application
对象的 Run
方法会被调用,这意味着应用程序进入了运行状态,开始处理消息循环。此时,应用程序将进入一个消息循环,等待用户输入和事件。
this.Run(); // 运行消息循环
Run()
方法的调用意味着应用程序开始接收和处理事件,直到应用程序退出。Application.Run()
是WPF程序的核心方法,它启动了事件处理循环,并且直到应用程序退出前,事件循环会一直运行。
5. 关闭阶段(Exit
事件)
应用程序结束时,WPF会触发 Exit
事件。此时,应用程序已经完全关闭,所有窗口和资源已经释放。你可以在 Exit
事件中执行一些资源清理的操作。
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
// 执行关闭前的清理操作,比如保存应用状态,释放资源等
}
}
ExitEventArgs
中包含了退出时的退出代码,通常是退出的原因或者状态代码。
6. 生命周期的各个重要事件
WPF的 Application
类提供了多个事件,允许开发者在应用程序的不同生命周期阶段插入自定义逻辑:
Startup
事件:在应用程序启动时触发。在这里可以处理启动时的逻辑。Activated
事件:在应用程序窗口被激活时触发。每次窗口被激活时都会触发。Deactivated
事件:当应用程序窗口失去焦点时触发。通常用于暂停某些操作或更新状态。Exit
事件:在应用程序退出时触发。用于资源清理等操作。
7. 退出阶段
退出阶段是应用程序生命周期的最后一个阶段。在这个阶段,WPF会销毁所有窗口并清理资源。一旦所有窗口关闭,Application.Run()
会返回,应用程序正式退出。
Application.Current.Shutdown();
调用 Shutdown()
方法会触发 Exit
事件并关闭应用程序。
8. Application的生命周期总结
- 加载
App.xaml
:系统加载应用程序配置和资源。 - 调用
OnStartup
:应用程序开始启动,执行初始化代码,创建并显示主窗口。 - 调用
Run
:应用程序进入消息循环,等待事件并响应用户交互。 - 调用
OnExit
:在应用程序退出时,执行清理操作。
小结
WPF应用程序的生命周期由 Application
类控制,涉及到多个重要的阶段:启动阶段、运行阶段、关闭阶段。Application
类为我们提供了丰富的事件和方法,可以用来管理和控制应用程序的各个生命周期阶段。理解这一生命周期对于有效管理WPF应用程序的状态、资源和用户交互非常关键。
源码
#region 程序集 PresentationFramework, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// C:\Program Files\dotnet\packs\Microsoft.WindowsDesktop.App.Ref\8.0.11\ref\net8.0\PresentationFramework.dll
#endregion
using System.Collections;
using System.Reflection;
using System.Windows.Markup;
using System.Windows.Navigation;
using System.Windows.Resources;
using System.Windows.Threading;
namespace System.Windows
{
//
// 摘要:
// Encapsulates a Windows Presentation Foundation application.
public class Application : DispatcherObject, IQueryAmbient
{
//
// 摘要:
// Initializes a new instance of the System.Windows.Application class.
//
// 异常:
// T:System.InvalidOperationException:
// More than one instance of the System.Windows.Application class is created per
// System.AppDomain.
public Application();
//
// 摘要:
// Gets or sets the System.Reflection.Assembly that provides the pack uniform resource
// identifiers (URIs) for resources in a WPF application.
//
// 返回结果:
// A reference to the System.Reflection.Assembly that provides the pack uniform
// resource identifiers (URIs) for resources in a WPF application.
//
// 异常:
// T:System.InvalidOperationException:
// A WPF application has an entry assembly, or System.Windows.Application.ResourceAssembly
// has already been set.
public static Assembly ResourceAssembly { get; set; }
//
// 摘要:
// Gets the System.Windows.Application object for the current System.AppDomain.
//
//
// 返回结果:
// The System.Windows.Application object for the current System.AppDomain.
public static Application Current { get; }
//
// 摘要:
// Gets or sets the main window of the application.
//
// 返回结果:
// A System.Windows.Window that is designated as the main application window.
//
// 异常:
// T:System.InvalidOperationException:
// System.Windows.Application.MainWindow is set from an application that's hosted
// in a browser, such as an XAML browser applications (XBAPs).
public Window MainWindow { get; set; }
//
// 摘要:
// Gets a collection of application-scope properties.
//
// 返回结果:
// An System.Collections.IDictionary that contains the application-scope properties.
public IDictionary Properties { get; }
//
// 摘要:
// Gets or sets a collection of application-scope resources, such as styles and
// brushes.
//
// 返回结果:
// A System.Windows.ResourceDictionary object that contains zero or more application-scope
// resources.
[Ambient]
public ResourceDictionary Resources { get; set; }
//
// 摘要:
// Gets or sets the condition that causes the System.Windows.Application.Shutdown
// method to be called.
//
// 返回结果:
// A System.Windows.ShutdownMode enumeration value. The default value is System.Windows.ShutdownMode.OnLastWindowClose.
public ShutdownMode ShutdownMode { get; set; }
//
// 摘要:
// Gets or sets a UI that is automatically shown when an application starts.
//
// 返回结果:
// A System.Uri that refers to the UI that automatically opens when an application
// starts.
//
// 异常:
// T:System.ArgumentNullException:
// System.Windows.Application.StartupUri is set with a value of null.
public Uri StartupUri { get; set; }
//
// 摘要:
// Gets the instantiated windows in an application.
//
// 返回结果:
// A System.Windows.WindowCollection that contains references to all window objects
// in the current System.AppDomain.
public WindowCollection Windows { get; }
//
// 摘要:
// Occurs when an application becomes the foreground application.
public event EventHandler Activated;
//
// 摘要:
// Occurs when an application stops being the foreground application.
public event EventHandler Deactivated;
//
// 摘要:
// Occurs just before an application shuts down and cannot be canceled.
public event ExitEventHandler Exit;
//
// 摘要:
// Occurs when a navigator in the application begins navigation to a content fragment,
// Navigation occurs immediately if the desired fragment is in the current content,
// or after the source XAML content has been loaded if the desired fragment is in
// different content.
public event FragmentNavigationEventHandler FragmentNavigation;
//
// 摘要:
// Occurs when content that was navigated to by a navigator in the application has
// been loaded, parsed, and has begun rendering.
public event LoadCompletedEventHandler LoadCompleted;
//
// 摘要:
// Occurs when the content that is being navigated to by a navigator in the application
// has been found, although it may not have completed loading.
public event NavigatedEventHandler Navigated;
//
// 摘要:
// Occurs when a new navigation is requested by a navigator in the application.
public event NavigatingCancelEventHandler Navigating;
//
// 摘要:
// Occurs when an error occurs while a navigator in the application is navigating
// to the requested content.
public event NavigationFailedEventHandler NavigationFailed;
//
// 摘要:
// Occurs periodically during a download that is being managed by a navigator in
// the application to provide navigation progress information.
public event NavigationProgressEventHandler NavigationProgress;
//
// 摘要:
// Occurs when the StopLoading method of a navigator in the application is called,
// or when a new navigation is requested by a navigator while a current navigation
// is in progress.
public event NavigationStoppedEventHandler NavigationStopped;
//
// 摘要:
// Occurs when an exception is thrown by an application but not handled.
public event DispatcherUnhandledExceptionEventHandler DispatcherUnhandledException;
//
// 摘要:
// Occurs when the user ends the Windows session by logging off or shutting down
// the operating system.
public event SessionEndingCancelEventHandler SessionEnding;
//
// 摘要:
// Occurs when the System.Windows.Application.Run method of the System.Windows.Application
// object is called.
public event StartupEventHandler Startup;
//
// 摘要:
// Returns a resource stream for a content data file that is located at the specified
// System.Uri (see WPF Application Resource, Content, and Data Files).
//
// 参数:
// uriContent:
// The relative System.Uri that maps to a loose resource.
//
// 返回结果:
// A System.Windows.Resources.StreamResourceInfo that contains a content data file
// that is located at the specified System.Uri. If a loose resource is not found,
// null is returned.
//
// 异常:
// T:System.ArgumentNullException:
// The System.Uri that is passed to System.Windows.Application.GetContentStream(System.Uri)
// is null.
//
// T:System.ArgumentException:
// The System.Uri that is passed to System.Windows.Application.GetContentStream(System.Uri)
// is an absolute System.Uri.
public static StreamResourceInfo GetContentStream(Uri uriContent);
//
// 摘要:
// Retrieves a cookie for the location specified by a System.Uri.
//
// 参数:
// uri:
// The System.Uri that specifies the location for which a cookie was created.
//
// 返回结果:
// A System.String value, if the cookie exists; otherwise, a System.ComponentModel.Win32Exception
// is thrown.
//
// 异常:
// T:System.ComponentModel.Win32Exception:
// A Win32 error is raised by the InternetGetCookie function (called by System.Windows.Application.GetCookie(System.Uri))
// if a problem occurs when attempting to retrieve the specified cookie.
public static string GetCookie(Uri uri);
//
// 摘要:
// Returns a resource stream for a site-of-origin data file that is located at the
// specified System.Uri (see WPF Application Resource, Content, and Data Files).
//
//
// 参数:
// uriRemote:
// The System.Uri that maps to a loose resource at the site of origin.
//
// 返回结果:
// A System.Windows.Resources.StreamResourceInfo that contains a resource stream
// for a site-of-origin data file that is located at the specified System.Uri. If
// the loose resource is not found, null is returned.
//
// 异常:
// T:System.ArgumentNullException:
// The System.Uri that is passed to System.Windows.Application.GetRemoteStream(System.Uri)
// is null.
//
// T:System.ArgumentException:
// The System.Uri that is passed to System.Windows.Application.GetRemoteStream(System.Uri)
// is either not relative, or is absolute but not in the pack://siteoforigin:,,,/
// form.
public static StreamResourceInfo GetRemoteStream(Uri uriRemote);
//
// 摘要:
// Returns a resource stream for a resource data file that is located at the specified
// System.Uri (see WPF Application Resource, Content, and Data Files).
//
// 参数:
// uriResource:
// The System.Uri that maps to an embedded resource.
//
// 返回结果:
// A System.Windows.Resources.StreamResourceInfo that contains a resource stream
// for resource data file that is located at the specified System.Uri.
//
// 异常:
// T:System.ArgumentNullException:
// The System.Uri that is passed to System.Windows.Application.GetResourceStream(System.Uri)
// is null.
//
// T:System.ArgumentException:
// The System.Uri that is passed to System.Windows.Application.GetResourceStream(System.Uri)
// is either not relative, or is absolute but not in the pack://application:,,,/
// form.
//
// T:System.IO.IOException:
// The System.Uri that is passed to System.Windows.Application.GetResourceStream(System.Uri)
// cannot be found.
public static StreamResourceInfo GetResourceStream(Uri uriResource);
//
// 摘要:
// Loads a XAML file that is located at the specified uniform resource identifier
// (URI) and converts it to an instance of the object that is specified by the root
// element of the XAML file.
//
// 参数:
// component:
// An object of the same type as the root element of the XAML file.
//
// resourceLocator:
// A System.Uri that maps to a relative XAML file.
//
// 异常:
// T:System.ArgumentNullException:
// resourceLocator is null.
//
// T:System.ArgumentException:
// The resourceLocator is an absolute URI.
//
// T:System.Exception:
// component is of a type that does not match the root element of the XAML file.
public static void LoadComponent(object component, Uri resourceLocator);
//
// 摘要:
// Loads a XAML file that is located at the specified uniform resource identifier
// (URI), and converts it to an instance of the object that is specified by the
// root element of the XAML file.
//
// 参数:
// resourceLocator:
// A System.Uri that maps to a relative XAML file.
//
// 返回结果:
// An instance of the root element specified by the XAML file loaded.
//
// 异常:
// T:System.ArgumentNullException:
// resourceLocator is null.
//
// T:System.ArgumentException:
// The resourceLocator is an absolute URI.
//
// T:System.Exception:
// The file is not a XAML file.
public static object LoadComponent(Uri resourceLocator);
//
// 摘要:
// Creates a cookie for the location specified by a System.Uri.
//
// 参数:
// uri:
// The System.Uri that specifies the location for which the cookie should be created.
//
//
// value:
// The System.String that contains the cookie data.
//
// 异常:
// T:System.ComponentModel.Win32Exception:
// A Win32 error is raised by the InternetSetCookie function (called by System.Windows.Application.SetCookie(System.Uri,System.String))
// if a problem occurs when attempting to create the specified cookie.
public static void SetCookie(Uri uri, string value);
//
// 摘要:
// Searches for a user interface (UI) resource, such as a System.Windows.Style or
// System.Windows.Media.Brush, with the specified key, and throws an exception if
// the requested resource is not found (see XAML Resources).
//
// 参数:
// resourceKey:
// The name of the resource to find.
//
// 返回结果:
// The requested resource object. If the requested resource is not found, a System.Windows.ResourceReferenceKeyNotFoundException
// is thrown.
//
// 异常:
// T:System.Windows.ResourceReferenceKeyNotFoundException:
// The resource cannot be found.
public object FindResource(object resourceKey);
//
// 摘要:
// Starts a Windows Presentation Foundation application.
//
// 返回结果:
// The System.Int32 application exit code that is returned to the operating system
// when the application shuts down. By default, the exit code value is 0.
//
// 异常:
// T:System.InvalidOperationException:
// System.Windows.Application.Run is called from a browser-hosted application (for
// example, an XAML browser application (XBAP)).
public int Run();
//
// 摘要:
// Starts a Windows Presentation Foundation application and opens the specified
// window.
//
// 参数:
// window:
// A System.Windows.Window that opens automatically when an application starts.
//
//
// 返回结果:
// The System.Int32 application exit code that is returned to the operating system
// when the application shuts down. By default, the exit code value is 0.
//
// 异常:
// T:System.InvalidOperationException:
// System.Windows.Application.Run is called from a browser-hosted application (for
// example, an XAML browser application (XBAP)).
public int Run(Window window);
//
// 摘要:
// Shuts down an application.
public void Shutdown();
//
// 摘要:
// Shuts down an application that returns the specified exit code to the operating
// system.
//
// 参数:
// exitCode:
// An integer exit code for an application. The default exit code is 0.
public void Shutdown(int exitCode);
//
// 摘要:
// Searches for the specified resource.
//
// 参数:
// resourceKey:
// The name of the resource to find.
//
// 返回结果:
// The requested resource object. If the requested resource is not found, a null
// reference is returned.
public object TryFindResource(object resourceKey);
//
// 摘要:
// Raises the System.Windows.Application.Activated event.
//
// 参数:
// e:
// An System.EventArgs that contains the event data.
protected virtual void OnActivated(EventArgs e);
//
// 摘要:
// Raises the System.Windows.Application.Deactivated event.
//
// 参数:
// e:
// An System.EventArgs that contains the event data.
protected virtual void OnDeactivated(EventArgs e);
//
// 摘要:
// Raises the System.Windows.Application.Exit event.
//
// 参数:
// e:
// An System.Windows.ExitEventArgs that contains the event data.
protected virtual void OnExit(ExitEventArgs e);
//
// 摘要:
// Raises the System.Windows.Application.FragmentNavigation event.
//
// 参数:
// e:
// A System.Windows.Navigation.FragmentNavigationEventArgs that contains the event
// data.
protected virtual void OnFragmentNavigation(FragmentNavigationEventArgs e);
//
// 摘要:
// Raises the System.Windows.Application.LoadCompleted event.
//
// 参数:
// e:
// A System.Windows.Navigation.NavigationEventArgs that contains the event data.
protected virtual void OnLoadCompleted(NavigationEventArgs e);
//
// 摘要:
// Raises the System.Windows.Application.Navigated event.
//
// 参数:
// e:
// A System.Windows.Navigation.NavigationEventArgs that contains the event data.
protected virtual void OnNavigated(NavigationEventArgs e);
//
// 摘要:
// Raises the System.Windows.Application.Navigating event.
//
// 参数:
// e:
// A System.Windows.Navigation.NavigatingCancelEventArgs that contains the event
// data.
protected virtual void OnNavigating(NavigatingCancelEventArgs e);
//
// 摘要:
// Raises the System.Windows.Application.NavigationFailed event.
//
// 参数:
// e:
// A System.Windows.Navigation.NavigationFailedEventArgs that contains the event
// data.
protected virtual void OnNavigationFailed(NavigationFailedEventArgs e);
//
// 摘要:
// Raises the System.Windows.Application.NavigationProgress event.
//
// 参数:
// e:
// A System.Windows.Navigation.NavigationProgressEventArgs that contains the event
// data.
protected virtual void OnNavigationProgress(NavigationProgressEventArgs e);
//
// 摘要:
// Raises the System.Windows.Application.NavigationStopped event.
//
// 参数:
// e:
// A System.Windows.Navigation.NavigationEventArgs that contains the event data.
protected virtual void OnNavigationStopped(NavigationEventArgs e);
//
// 摘要:
// Raises the System.Windows.Application.SessionEnding event.
//
// 参数:
// e:
// A System.Windows.SessionEndingCancelEventArgs that contains the event data.
protected virtual void OnSessionEnding(SessionEndingCancelEventArgs e);
//
// 摘要:
// Raises the System.Windows.Application.Startup event.
//
// 参数:
// e:
// A System.Windows.StartupEventArgs that contains the event data.
protected virtual void OnStartup(StartupEventArgs e);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)