Введение в Windows Forms
Для создания графических интерфейсов с помощью платформы .NET применяются разные технологии — Window Forms, WPF, приложения для магазина Windows Store (для ОС Windows 8/8.1/10). Однако наиболее простой и удобной платформой до сих пор остается Window Forms или формы. Данное руководство ставит своей целью дать понимание принципов создания графических интерфейсов с помощью технологии WinForms и работы основных элементов управления.
Создание графического приложения
Для создания графического проекта нам потребуется среда разработки Visual Studio. Поскольку наиболее распространенная пока версия Visual Studio 2013, то для данного руководства я буду использовать бесплатную версию данной среды Visual Studio Community 2013 которую можно найти на странице https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx.
После установки среды и всех ее компонентов, запустим Visual Studio и создадим проект графического приложения. Для этого в меню выберем пункт File (Файл) и в подменю выберем New — > Project (Создать — > Проект). После этого перед нами откроется диалоговое окно создания нового проекта:
В левой колонке выберем Windows Desktop , а в центральной части среди типов проектов — тип Windows Forms Application и дадим ему какое-нибудь имя в поле внизу. Например, назовем его HelloApp. После этого нажимаем OK.
После этого Visual Studio откроет наш проект с созданными по умолчанию файлами:
Большую часть пространства Visual Studio занимает графический дизайнер, который содержит форму будущего приложения. Пока она пуста и имеет только заголовок Form1. Справа находится окно файлов решения/проекта — Solution Explorer (Обозреватель решений). Там и находятся все связанные с нашим приложением файлы, в том числе файлы формы Form1.cs.
Внизу справа находится окно свойств — Properties. Так как у меня в данный момент выбрана форма как элемент управления, то в этом поле отображаются свойства, связанные с формой.
Теперь найдем в этом окне свойство формы Text и изменим его значение на любое другое:
Таким образом мы поменяли заголовок формы. Теперь перенесем на поле какой-нибудь элемент управления, например, кнопку. Для этого найдем в левой части Visual Studio вкладку Toolbox (Панель инструментов) . Нажмем на эту вкладку, и у нас откроется панель с элементами, откуда мы можем с помощью мыши перенести на форму любой элемент:
Найдем среди элементов кнопку и, захватив ее указателем мыши, перенесем на форму:
Это визуальная часть. Теперь приступим к самому программированию. Добавим простейший код на языке C#, который бы выводил сообщение по нажатию кнопки. Для этого мы должны перейти в файл кода, который связан с этой формой. Если у нас не открыт файл кода, мы можем нажать на форму правой кнопкой мыши и в появившемся меню выбрать View Code (Посмотреть файл кода):
Однако воспользуемся другим способом, чтобы не писать много лишнего кода. Наведем указатель мыши на кнопку и щелкнем по ней двойным щелчком. Мы автоматически попадаем в файл кода Form1.cs, который выглядит так:
Добавим вывод сообщения по нажатию кнопки, изменив код следующим образом:
Запуск приложения
Чтобы запустить приложение в режиме отладки, нажмем на клавишу F5 или на зеленую стрелочку на панели Visual Studio. После этого запустится наша форма с одинокой кнопкой. И если мы нажмем на кнопку на форме, то нам будет отображено сообщение с приветствием.
После запуска приложения студия компилирует его в файл с расширением exe. Найти данный файл можно, зайдя в папку проекта и далее в каталог bin/Debug или bin/Release
Рассмотрев вкратце создание проекта графического приложения, мы можем перейти к обзору основных компонентов и начнем мы с форм.
Application Class
Definition
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.
Examples
The following code example lists numbers in a list box on a form. Each time you click button1 , the application adds another number to the list.
The Main method calls Run to start the application, which creates the form, listBox1 and button1 . When the user clicks button1 , the button1_Click method displays a MessageBox. If the user clicks No on the MessageBox, the button1_Click method adds a number to the list. If the user clicks Yes , the application calls Exit to process all remaining messages in the queue and then to quit.
The call to Exit will fail in partial trust.
Remarks
The Application class has methods to start and stop applications and threads, and to process Windows messages, as follows:
Run starts an application message loop on the current thread and, optionally, makes a form visible.
Exit or ExitThread stops a message loop.
DoEvents processes messages while your program is in a loop.
AddMessageFilter adds a message filter to the application message pump to monitor Windows messages.
IMessageFilter lets you stop an event from being raised or perform special operations before invoking an event handler.
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.
Properties
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.
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.
Methods
Adds a message filter to monitor Windows messages as they are routed to their destinations.
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.
(Inherited from 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.
(Inherited from Object)
Gets the Type of the current instance.
(Inherited from Object)
Creates a shallow copy of the current Object.
(Inherited from Object)
Initializes OLE on the current thread.
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.
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.
Sets the application-wide default for the UseCompatibleTextRendering property defined on certain controls.
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.
(Inherited from Object)
Events
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. When the main thread for an application is about to be shut down, this event is raised first, followed by an ApplicationExit event.
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.