Application Класс
Определение
Инкапсулирует приложение Windows Presentation Foundation. Encapsulates a Windows Presentation Foundation application.
Примеры
В следующем примере показано, как стандартное приложение определяется с использованием только разметки: The following example shows how a standard application is defined using only markup:
В следующем примере показано, как стандартное приложение определяется с использованием только кода. The following example shows how a standard application is defined using only code:
В следующем примере показано определение стандартного приложения с помощью сочетания разметки и кода программной части. The following example shows how a standard application is defined using a combination of markup and code-behind.
Комментарии
Application — Это класс, инкапсулирующий функции WPF, относящиеся к приложению, включая следующие: Application is a class that encapsulates WPF application-specific functionality, including the following:
Параметры командной строки и обработка кода выхода: Application.Startup , Application.Exit , Application.Shutdown . Command-Line Parameter and Exit Code Processing: Application.Startup, Application.Exit, Application.Shutdown.
Application реализует Одноэлементный шаблон для предоставления общего доступа к службам окна, свойства и области ресурсов. Application implements the singleton pattern to provide shared access to its window, property, and resource scope services. Следовательно, для каждого экземпляра можно создать только один экземпляр Application класса AppDomain . Consequently, only one instance of the Application class can be created per AppDomain.
Можно реализовать Application с помощью разметки, разметки и кода программной части или кода. You can implement an Application using markup, markup and code-behind, or code. Если Application реализуется с разметкой (разметка или разметка и код программной части), то файл разметки должен быть настроен как элемент Microsoft Build Engine (MSBuild) ApplicationDefinition . If Application is implemented with markup, whether markup or markup and code-behind, the markup file must be configured as an Microsoft build engine (MSBuild) ApplicationDefinition item.
Для автономного приложения не требуется Application объект; можно реализовать пользовательский static метод точки входа ( Main ), который открывает окно без создания экземпляра Application . A standalone application does not require an Application object; it is possible to implement a custom static entry point method ( Main ) that opens a window without creating an instance of Application. Однако для приложений браузера XAML (XBAP) требуется Application объект. However, XAML browser applications (XBAPs) require an Application object.
Конструкторы
Инициализирует новый экземпляр класса Application. Initializes a new instance of the Application class.
Свойства
Возвращает объект Application для текущего AppDomain. Gets the Application object for the current AppDomain.
Возвращает объект Dispatcher, с которым связан этот объект DispatcherObject. Gets the Dispatcher this DispatcherObject is associated with.
(Унаследовано от DispatcherObject)
Получает или задает главное окно приложения. Gets or sets the main window of the application.
Возвращает коллекцию свойств области приложения. Gets a collection of application-scope properties.
Возвращает или задает объект Assembly , предоставляющий универсальные идентификаторы ресурсов (URI) Pack для ресурсов в приложении WPF. Gets or sets the Assembly that provides the pack uniform resource identifiers (URIs) for resources in a WPF application.
Получает или задает коллекцию ресурсов области приложения, например, стилей и кистей. Gets or sets a collection of application-scope resources, such as styles and brushes.
Получает или задает условие, которое является причиной вызова метода Shutdown(). Gets or sets the condition that causes the Shutdown() method to be called.
Получает или задает пользовательский интерфейс, отображающееся автоматически при запуске приложения. Gets or sets a UI that is automatically shown when an application starts.
Возвращает созданные окна приложения. Gets the instantiated windows in an application.
Методы
Определяет, имеет ли вызывающий поток доступ к этому DispatcherObject. Determines whether the calling thread has access to this DispatcherObject.
(Унаследовано от DispatcherObject)
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Выполняет поиск ресурса пользовательского интерфейса (например Style Brush , или) с указанным ключом и создает исключение, если запрошенный ресурс не найден (см. раздел ресурсы XAML). Searches for a user interface (UI) resource, such as a Style or Brush, with the specified key, and throws an exception if the requested resource is not found (see XAML Resources).
Возвращает поток ресурса для файла данных содержания, расположенного в указанном Uri (см. Ресурсы, содержимое и файлы данных WPF-приложения). Returns a resource stream for a content data file that is located at the specified Uri (see WPF Application Resource, Content, and Data Files).
Возвращает файл cookie для расположения, указанного Uri. Retrieves a cookie for the location specified by a Uri.
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Возвращает поток ресурса для исходного файла данных ресурса, расположенного в указанном Uri (см. Ресурсы, содержимое и файлы данных WPF-приложения). Returns a resource stream for a site-of-origin data file that is located at the specified Uri (see WPF Application Resource, Content, and Data Files).
Возвращает поток ресурса для файла данных ресурса, расположенного в указанном Uri (см. Ресурсы, содержимое и файлы данных WPF-приложения). Returns a resource stream for a resource data file that is located at the specified Uri (see WPF Application Resource, Content, and Data Files).
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Загружает XAML-файл, расположенный по указанному универсальному идентификатору ресурса (URI), и преобразует его в экземпляр объекта, указанный в корневом элементе файла XAML. 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.
Загружает XAML-файл, расположенный по указанному универсальному идентификатору ресурса (URI), и преобразует его в экземпляр объекта, указанный в корневом элементе файла XAML. 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.
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Вызывает событие Activated. Raises the Activated event.
Вызывает событие Deactivated. Raises the Deactivated event.
Вызывает событие Exit. Raises the Exit event.
Вызывает событие LoadCompleted. Raises the LoadCompleted event.
Вызывает событие Navigated. Raises the Navigated event.
Вызывает событие Navigating. Raises the Navigating event.
Вызывает событие NavigationFailed. Raises the NavigationFailed event.
Вызывает событие SessionEnding. Raises the SessionEnding event.
Вызывает событие Startup. Raises the Startup event.
Запускает приложение Windows Presentation Foundation. Starts a Windows Presentation Foundation application.
Запускает приложение Windows Presentation Foundation с открытием указанного окна. Starts a Windows Presentation Foundation application and opens the specified window.
Создает файл cookie для расположения, указанного Uri. Creates a cookie for the location specified by a Uri.
Завершить работу приложения. Shuts down an application.
Завершает работу приложения и передает указанный код завершения операционной системой. Shuts down an application that returns the specified exit code to the operating system.
Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.
(Унаследовано от Object)
Осуществляет поиск указанного ресурса. Searches for the specified resource.
Обеспечивает наличие у вызывающего потока доступ к этому DispatcherObject. Enforces that the calling thread has access to this DispatcherObject.
(Унаследовано от DispatcherObject)
События
Происходит, когда приложение становиться активным. Occurs when an application becomes the foreground application.
Происходит, когда приложение перестает быть активным. Occurs when an application stops being the foreground application.
Происходит при генерации приложением исключения, которое не обрабатывается. Occurs when an exception is thrown by an application but not handled.
Происходит непосредственно перед завершением работы приложения и его отменой. Occurs just before an application shuts down and cannot be canceled.
Происходит, когда навигатор в приложении начинает переход к фрагменту содержимого, переход происходит немедленно, если нужный фрагмент находится в текущем содержимом, или после загрузки исходного содержимого XAML, если нужный фрагмент находится в другом содержимом. 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.
Происходит после того, как содержимое, переданное приложению, было загружено, проанализировано и отрисовывается. Occurs when content that was navigated to by a navigator in the application has been loaded, parsed, and has begun rendering.
Происходит, когда содержимое, к которому осуществляется переход, найдено, хотя его загрузка, возможно, еще не завершена. 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.
Происходит при запросе приложением перехода. Occurs when a new navigation is requested by a navigator in the application.
Происходит, когда происходит ошибка при переходе к указанному содержимому. Occurs when an error occurs while a navigator in the application is navigating to the requested content.
Происходит время от времени во время загрузки, управляемой приложением для предоставления информации о статусе загрузки. Occurs periodically during a download that is being managed by a navigator in the application to provide navigation progress information.
Появляется при вызове метода перехода приложения StopLoading , или когда поступил запрос нового перехода во время выполнения текущего. 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.
Происходит, когда пользователь завершает сеанс Windows, выходя из системы или завершая работу операционной системы. Occurs when the user ends the Windows session by logging off or shutting down the operating system.
Происходит при вызове метода Run() объекта Application. Occurs when the Run() method of the Application object is called.
Явные реализации интерфейса
Запрашивает, доступно ли заданное внешнее свойство в текущей области. Queries for whether a specified ambient property is available in the current scope.
Применяется к
Потокобезопасность
Открытые static ( Shared в Visual Basic) члены этого типа являются потокобезопасными. The public static ( Shared in Visual Basic) members of this type are thread safe. Кроме того, FindResource(Object) методы и TryFindResource(Object) и свойства и Properties Resources являются потокобезопасными. In addition, the FindResource(Object) and TryFindResource(Object) methods and the Properties and Resources properties are thread safe.
Application Класс
Определение
Предоставляет методы и свойства static для управления приложением, например методы для запуска и остановки приложения, для обработки сообщений Windows и свойства для получения сведений о приложении. Provides static methods and properties to manage an application, such as methods to start and stop an application, to process Windows messages, and properties to get information about an application. Этот класс не наследуется. This class cannot be inherited.
Примеры
В следующем примере кода показаны числа из списка в форме. The following code example lists numbers in a list box on a form. Каждый раз при щелчке button1 приложение добавляет в список еще один номер. Each time you click button1 , the application adds another number to the list.
Main Метод вызывает Run , чтобы запустить приложение, которое создает форму listBox1 и button1 . The Main method calls Run to start the application, which creates the form, listBox1 and button1 . Когда пользователь нажимает кнопку button1 , button1_Click метод отображает MessageBox . When the user clicks button1 , the button1_Click method displays a MessageBox. Если пользователь нажимает кнопку No MessageBox , button1_Click метод добавляет число в список. If the user clicks No on the MessageBox, the button1_Click method adds a number to the list. Если пользователь нажимает кнопку Yes , приложение вызывает Exit для обработки всех оставшихся сообщений в очереди, а затем завершает работу. If the user clicks Yes , the application calls Exit to process all remaining messages in the queue and then to quit.
Вызов метода Exit приведет к сбою при частичном доверии. The call to Exit will fail in partial trust.
Комментарии
ApplicationКласс содержит методы запуска и завершения приложений и потоков, а также для обработки сообщений Windows следующим образом: The Application class has methods to start and stop applications and threads, and to process Windows messages, as follows:
Run запускает цикл обработки сообщений приложения в текущем потоке и, при необходимости, делает форму видимой. Run starts an application message loop on the current thread and, optionally, makes a form visible.
Exit или ExitThread останавливает цикл обработки сообщений. Exit or ExitThread stops a message loop.
DoEvents обрабатывает сообщения, пока программа находится в цикле. DoEvents processes messages while your program is in a loop.
AddMessageFilter Добавляет фильтр сообщений в конвейер обмена сообщениями приложения для отслеживания сообщений Windows. AddMessageFilter adds a message filter to the application message pump to monitor Windows messages.
IMessageFilter позволяет предотвращать возникновение события или выполнять специальные операции перед вызовом обработчика событий. IMessageFilter lets you stop an event from being raised or perform special operations before invoking an event handler.
Этот класс содержит CurrentCulture Свойства и, CurrentInputLanguage позволяющие получить или задать сведения о языке и региональных параметрах для текущего потока. This class has CurrentCulture and CurrentInputLanguage properties to get or set culture information for the current thread.
Нельзя создать экземпляр этого класса. You cannot create an instance of this class.
Свойства
Получает значение, определяющее, может ли вызывающий объект выйти из этого приложения. Gets a value indicating whether the caller can quit this application.
Получает путь для данных приложения, являющихся общими для всех пользователей. Gets the path for the application data that is shared among all users.
Получает раздел реестра для данных приложения, являющихся общими для всех пользователей. Gets the registry key for the application data that is shared among all users.
Возвращает название компании, сопоставленное с приложением. Gets the company name associated with the application.
Получает или задает данные о языке и региональных параметрах для текущего потока. Gets or sets the culture information for the current thread.
Получает или задает текущий язык ввода для текущего потока. Gets or sets the current input language for the current thread.
Получает путь для исполняемого файла, запустившего приложение, включая исполняемое имя. Gets the path for the executable file that started the application, including the executable name.
Возвращает текущий режим высокого DPI для данного приложения. Gets the current high DPI mode for the application.
Получает путь для данных приложения локального неперемещающегося пользователя. Gets the path for the application data of a local, non-roaming user.
Получает значение, указывающее, существует ли цикл обработки сообщений в данном потоке. Gets a value indicating whether a message loop exists on this thread.
Получает коллекцию открытых форм, принадлежащих приложению. Gets a collection of open forms owned by the application.
Получает название продукта, сопоставленного с данным приложением. Gets the product name associated with this application.
Получает версию продукта, сопоставленную с данным приложением. Gets the product version associated with this application.
Получает значение, указывающее, будет ли текущее приложение прорисовывать элементы управления с помощью визуальных стилей. Gets a value specifying whether the current application is drawing controls with visual styles.
Получает или задает строку формата для использования в заголовках окон верхнего уровня, когда они отображаются с предупреждающим объявлением. Gets or sets the format string to apply to top-level window captions when they are displayed with a warning banner.
Получает путь для исполняемого файла, запустившего приложение, не включая исполняемое имя. Gets the path for the executable file that started the application, not including the executable name.
Получает путь для данных приложения пользователя. Gets the path for the application data of a user.
Получает раздел реестра для данных приложения пользователя. Gets the registry key for the application data of a user.
Возвращает значение, указывающее, включены ли визуальные стили для приложения. Gets a value that indicates whether visual styles are enabled for the application.
Получает или задает значение, которое указывает, используется ли курсор ожидания для всех открытых форм приложения. Gets or sets whether the wait cursor is used for all open forms of the application.
Получает значение, указывающее, каким образом визуальные стили применяются к окну приложения. Gets a value that specifies how visual styles are applied to application windows.
Методы
Добавляет фильтр сообщений для мониторинга сообщений Windows при их маршрутизации к местам назначения. Adds a message filter to monitor Windows messages as they are routed to their destinations.
Обрабатывает все сообщения Windows, которые в данный момент находятся в очереди сообщений. Processes all Windows messages currently in the message queue.
Включает визуальные стили для приложения. Enables visual styles for the application.
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Сообщает всем средствам переноса сообщений, что они должны завершить работу, а затем закрывает все окна приложения после обработки сообщений. Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.
Сообщает всем средствам переноса сообщений, что они должны завершить работу, а затем закрывает все окна приложения после обработки сообщений. Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.
Выходит из цикла обработки сообщений в текущем потоке и закрывает все окна в потоке. Exits the message loop on the current thread and closes all windows on the thread.
Запускает любые фильтры для сообщения окна и возвращает копию измененного сообщения. Runs any filters against a window message, and returns a copy of the modified message.
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Инициализирует OLE в текущем потоке. Initializes OLE on the current thread.
Вызывает событие ThreadException. Raises the ThreadException event.
Вызывает событие Idle в размещенных скриптах. Raises the Idle event in hosted scenarios.
Регистрирует ответный вызов, чтобы проверить, выполняется ли цикл обработки сообщений в размещенных средах. Registers a callback for checking whether the message loop is running in hosted environments.
Удаляет фильтр сообщений из средства переноса сообщений приложения. Removes a message filter from the message pump of the application.
Завершает работу приложения и немедленно запускает новый экземпляр. Shuts down the application and starts a new instance immediately.
Запускает стандартный цикл обработки сообщений приложения в текущем потоке, без формы. Begins running a standard application message loop on the current thread, without a form.
Запускает стандартный цикл обработки сообщений приложения в текущем потоке с ApplicationContext. Begins running a standard application message loop on the current thread, with an ApplicationContext.
Запускает стандартный цикл обработки сообщений приложения в текущем потоке и делает указанную форму видимой. Begins running a standard application message loop on the current thread, and makes the specified form visible.
Задает значения по умолчанию во всем приложении для свойства UseCompatibleTextRendering , определенного в конкретных элементах управления. Sets the application-wide default for the UseCompatibleTextRendering property defined on certain controls.
Задает режим высокого DPI процесса. Sets the high DPI mode of the process.
Приостанавливает работу системы или переводит ее в спящий режим или же запрашивает приостановку работы системы или перевод ее в спящий режим. Suspends or hibernates the system, or requests that the system be suspended or hibernated.
Указывает, как приложение должно реагировать на необработанные исключения. Instructs the application how to respond to unhandled exceptions.
Предоставляет приложению инструкции, определяющие, как приложение должно отвечать на необработанные исключения, при необходимости применяя поведение, зависящее от потока. Instructs the application how to respond to unhandled exceptions, optionally applying thread-specific behavior.
Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.
(Унаследовано от Object)
Отменяет регистрацию ответного вызова цикла обработки сообщений, сделанного с помощью метода RegisterMessageLoop(Application+MessageLoopCallback). Unregisters the message loop callback made with RegisterMessageLoop(Application+MessageLoopCallback).
События
Происходит при закрытии приложения. Occurs when the application is about to shut down.
Происходит при переходе приложения в модальное состояние. Occurs when the application is about to enter a modal state.
Происходит, когда приложение заканчивает обработку и собирается перейти в состояние простоя. Occurs when the application finishes processing and is about to enter the idle state.
Возникает, когда приложение собирается выйти из модального состояния. Occurs when the application is about to leave a modal state.
Происходит при выдаче неперехваченного исключения потока. Occurs when an untrapped thread exception is thrown.
Происходит при закрытии потока. Occurs when a thread is about to shut down. Перед закрытием главного потока для приложения вызывается данное событие, за которым следует событие ApplicationExit. When the main thread for an application is about to be shut down, this event is raised first, followed by an ApplicationExit event.