- Application. Run Метод
- Определение
- Перегрузки
- Возвращаемое значение
- Исключения
- Примеры
- Комментарии
- How to: Create a Windows Forms application from the command line
- Procedure
- To create the form
- To compile and run the application
- Adding a control and handling an event
- To declare a button control and handle its click event
- Example
- Application. Run Method
- Definition
- Overloads
- Exceptions
- Remarks
- See also
- Applies to
- Run(ApplicationContext)
- Parameters
- Exceptions
- Examples
- Как создать Windows Forms приложение из командной строки How to: Create a Windows Forms application from the command line
- Процедура Procedure
- Создание формы To create the form
- Компиляция и запуск приложения To compile and run the application
- Добавление элемента управления и обработка события Adding a control and handling an event
- Объявление элемента управления типа «Кнопка» и обработка событий щелчка мышью для нее To declare a button control and handle its click event
- Пример Example
Application. Run Метод
Определение
Запускает приложение Windows Presentation Foundation. Starts a Windows Presentation Foundation application.
Перегрузки
Запускает приложение Windows Presentation Foundation. Starts a Windows Presentation Foundation application.
Запускает приложение Windows Presentation Foundation с открытием указанного окна. Starts a Windows Presentation Foundation application and opens the specified window.
Запускает приложение Windows Presentation Foundation. Starts a Windows Presentation Foundation application.
Возвращаемое значение
Код выхода Int32, возвращаемый приложением в операционную систему при завершении работы приложения. The Int32 application exit code that is returned to the operating system when the application shuts down. По умолчанию, код выхода равен 0. By default, the exit code value is 0.
Исключения
Run() вызывается из приложения, размещенного в браузере (например, приложения браузера XAML (XBAP)). Run() is called from a browser-hosted application (for example, an XAML browser application (XBAP)).
Примеры
В следующем примере показано приложение, которое использует пользовательский объект Application и поэтому должен явно вызывать метод Run . The following example shows an application that uses a custom Application and must therefore explicitly call Run.
Комментарии
Run вызывается для запуска приложения WPF. Run is called to start a WPF application. При определении Application с помощью разметки или разметки и кода программной части Run будет вызываться неявно. If you define your Application using markup, or markup and code-behind, Run will be called implicitly. Однако при определении Application с помощью кода необходимо явно вызвать метод Run . However, if you define your Application using code, you will need to explicitly call Run.
При Run вызове метода Application присоединяет новый Dispatcher экземпляр к потоку пользовательского интерфейса. When Run is called, Application attaches a new Dispatcher instance to the UI thread. Затем Dispatcher Run вызывается метод объекта, который запускает конвейер сообщений для обработки сообщений Windows. Next, the Dispatcher object’s Run method is called, which starts a message pump to process windows messages. Наконец, Dispatcher объект вызывает Application OnStartup метод объекта для вызова Startup события. Finally, the Dispatcher object calls the Application object’s the OnStartup method to raise the Startup event. Следовательно, модель выполнения приложения была установлена на время обработки Startup , после чего приложение считается запущенным. Consequently, the application execution model has been established by the time you handle Startup, at which point the application is considered to be running.
Приложение прекращает выполнение при Shutdown вызове; значение ShutdownMode свойства определяет Shutdown , когда вызывается, и происходит ли его автоматическое или необходимо явно вызывать. An application stops running when Shutdown is called; the value of the ShutdownMode property determines when Shutdown is called, and whether it happens automatically or you need to explicitly call it.
Run может вызываться только из потока, который создает Application объект. Run can be called only from the thread that creates the Application object. Кроме того, Run нельзя вызывать из XBAP. Also, Run cannot be called from a XBAP.
How to: Create a Windows Forms application from the command line
The following procedures describe the basic steps that you must complete to create and run a Windows Forms application from the command line. There is extensive support for these procedures in Visual Studio. Also see Walkthrough: Hosting a Windows Forms Control in WPF.
Procedure
To create the form
In an empty code file, type the following Imports or using statements:
Declare a class named Form1 that inherits from the Form class:
Create a parameterless constructor for Form1 .
You will add more code to the constructor in a subsequent procedure.
Add a Main method to the class.
Apply the STAThreadAttribute to the C# Main method to specify your Windows Forms application is a single-threaded apartment. (The attribute is not necessary in Visual Basic, since Windows forms applications developed with Visual Basic use a single-threaded apartment model by default.)
Call EnableVisualStyles to apply operating system styles to your application.
Create an instance of the form and run it.
To compile and run the application
At the .NET Framework command prompt, navigate to the directory you created the Form1 class.
Compile the form.
If you are using C#, type: csc form1.cs
If you are using Visual Basic, type: vbc form1.vb
At the command prompt, type: Form1.exe
Adding a control and handling an event
The previous procedure steps demonstrated how to just create a basic Windows Form that compiles and runs. The next procedure will show you how to create and add a control to the form, and handle an event for the control. For more information about the controls you can add to Windows Forms, see Windows Forms Controls.
In addition to understanding how to create Windows Forms applications, you should understand event-based programming and how to handle user input. For more information, see Creating Event Handlers in Windows Forms, and Handling User Input
To declare a button control and handle its click event
Declare a button control named button1 .
In the constructor, create the button and set its Size, Location and Text properties.
Add the button to the form.
The following code example demonstrates how to declare the button control:
Create a method to handle the Click event for the button.
In the click event handler, display a MessageBox with the message, «Hello World».
The following code example demonstrates how to handle the button control’s click event:
Associate the Click event with the method you created.
The following code example demonstrates how to associate the event with the method.
Compile and run the application as described in the previous procedure.
Example
The following code example is the complete example from the previous procedures:
Application. Run Method
Definition
Begins running a standard application message loop on the current thread.
Overloads
Begins running a standard application message loop on the current thread, without a form.
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.
Begins running a standard application message loop on the current thread, without a form.
Exceptions
A main message loop is already running on this thread.
Remarks
In a Win32-based or Windows Forms application, a message loop is a routine in code that processes user events, such as mouse clicks and keyboard strokes. Every running Windows-based application requires an active message loop, called the main message loop. When the main message loop is closed, the application exits. In Windows Forms, this loop is closed when the Exit method is called, or when the ExitThread method is called on the thread that is running the main message loop.
Most Windows Forms developers will not need to use this version of the method. You should use the Run(Form) overload to start an application with a main form, so that the application terminates when the main form is closed. For all other situations, use the Run(ApplicationContext) overload, which supports supplying an ApplicationContext object for better control over the lifetime of the application.
See also
Applies to
Run(ApplicationContext)
Begins running a standard application message loop on the current thread, with an ApplicationContext.
Parameters
An ApplicationContext in which the application is run.
Exceptions
A main message loop is already running on this thread.
Examples
The example displays two forms and exits the application when both forms are closed. When the application starts and exits, the position of each form is remembered. This example demonstrates how to use an ApplicationContext, along with the Application.Run(context) method, to display multiple forms when the application starts.
The class MyApplicationContext inherits from ApplicationContext and keeps track when each form is closed, and exits the current thread when they both are. The class stores the positions of each form for the user. The form position data is stored in a file titled Appdata.txt that is created in the location determined by UserAppDataPath. The Main method calls Application.Run(context) to start the application given the ApplicationContext.
The code for the AppForm1 and AppForm2 forms is not shown for the purpose of brevity. See the ApplicationContext class overview for the whole code listing.
Как создать Windows Forms приложение из командной строки How to: Create a Windows Forms application from the command line
В процедурах ниже описаны основные шаги, которые необходимо выполнить для создания и запуска приложения Windows Forms из командной строки. The following procedures describe the basic steps that you must complete to create and run a Windows Forms application from the command line. Visual Studio предлагает расширенную поддержку этих процедур. There is extensive support for these procedures in Visual Studio. См. также раздел Пошаговое руководство. размещение элемента управления Windows Forms в WPF. Also see Walkthrough: Hosting a Windows Forms Control in WPF.
Процедура Procedure
Создание формы To create the form
В пустом файле кода введите следующую Imports using инструкцию или: In an empty code file, type the following Imports or using statements:
Объявите класс с именем Form1 , наследуемый от класса Form: Declare a class named Form1 that inherits from the Form class:
Создайте конструктор без параметров для Form1 . Create a parameterless constructor for Form1 .
В следующий процедуре будет добавлен дополнительный код конструктора. You will add more code to the constructor in a subsequent procedure.
Добавьте в класс метод Main . Add a Main method to the class.
Примените STAThreadAttribute к Main методу C#, чтобы указать Windows Forms приложение является однопотоковым апартаментом. Apply the STAThreadAttribute to the C# Main method to specify your Windows Forms application is a single-threaded apartment. (Атрибут не является обязательным в Visual Basic, так как приложения Windows Forms, разработанные с помощью Visual Basic, по умолчанию используют модель апартамента с одним потоком.) (The attribute is not necessary in Visual Basic, since Windows forms applications developed with Visual Basic use a single-threaded apartment model by default.)
Вызовите EnableVisualStyles , чтобы применить стили операционной системы к приложению. Call EnableVisualStyles to apply operating system styles to your application.
Создайте экземпляр формы и запустите его. Create an instance of the form and run it.
Компиляция и запуск приложения To compile and run the application
В командной строке .NET Framework перейдите к папке, в которой содержится класс Form1 . At the .NET Framework command prompt, navigate to the directory you created the Form1 class.
Скомпилируйте форму. Compile the form.
Если используется C#, введите: csc form1.cs If you are using C#, type: csc form1.cs
При использовании Visual Basic введите: vbc form1.vb If you are using Visual Basic, type: vbc form1.vb
В командной строке введите следующий текст: Form1.exe . At the command prompt, type: Form1.exe
Добавление элемента управления и обработка события Adding a control and handling an event
В предыдущей процедуре продемонстрировано, как создать простейшую форму Windows Forms, скомпилировать и запустить ее. The previous procedure steps demonstrated how to just create a basic Windows Form that compiles and runs. В следующей процедуре будет показано, как создать и добавить в форму элемент управления и как обрабатывать событие для него. The next procedure will show you how to create and add a control to the form, and handle an event for the control. Дополнительные сведения об элементах управления, которые можно добавить в Windows Forms, см. в разделе элементы управления Windows Forms. For more information about the controls you can add to Windows Forms, see Windows Forms Controls.
Помимо понимания способов создания приложений Windows Forms, следует обладать общими знаниями о программировании на основе событий и способах обработки данных, введенных пользователем. In addition to understanding how to create Windows Forms applications, you should understand event-based programming and how to handle user input. Дополнительные сведения см. в статьях Создание обработчиков событий в Windows Formsи обработка входных данных пользователя . For more information, see Creating Event Handlers in Windows Forms, and Handling User Input
Объявление элемента управления типа «Кнопка» и обработка событий щелчка мышью для нее To declare a button control and handle its click event
Объявите элемент управления типа «Кнопка» с именем button1 . Declare a button control named button1 .
В конструкторе создайте кнопку и задайте ее свойства Size, Location и Text. In the constructor, create the button and set its Size, Location and Text properties.
Добавьте кнопку в форму. Add the button to the form.
В следующем примере кода показано, как объявить элемент управления Button: The following code example demonstrates how to declare the button control:
Создайте метод для обработки события Click для кнопки. Create a method to handle the Click event for the button.
В обработчике событий щелчка мышью выведите элемент управления MessageBox с сообщением «Здравствуй, мир». In the click event handler, display a MessageBox with the message, «Hello World».
В следующем примере кода показано, как обрабатывается событие Click элемента управления Button: The following code example demonstrates how to handle the button control’s click event:
Свяжите событие Click с созданным методом. Associate the Click event with the method you created.
В примере кода ниже показано, как связать событие с методом. The following code example demonstrates how to associate the event with the method.
Скомпилируйте и запустите приложение, как описано в предыдущей процедуре. Compile and run the application as described in the previous procedure.
Пример Example
В следующем примере кода приведен полный пример из предыдущих процедур. The following code example is the complete example from the previous procedures: