Windows Forms
Windows Forms (WinForms) is a UI framework for building Windows desktop applications. It is a .NET wrapper over Windows user interface libraries, such as User32 and GDI+. It also offers controls and other functionality that is unique to Windows Forms.
Windows Forms also provides one of the most productive ways to create desktop applications based on the visual designer provided in Visual Studio. It enables drag-and-drop of visual controls and other similar functionality that make it easy to build desktop applications.
Windows Forms Out-Of-Process Designer
For information about the WinForms Designer supporting the .NET runtime and the changes between the .NET Framework Designer (supporting .NET Framework up to version 4.8.1) vs. the .NET Designer (supporting .NET 6, 7, 8, 9+), please see Windows Forms Designer Documentation.
Important: As a Third Party Control Vendor, when you migrate controls from .NET Framework to .NET, your control libraries at runtime are expected to work as before in the context of the respective new TFM (special modernization or security changes in the TFM kept aside, but those are rare breaking changes). Depending on the richness of your control’s design-time support, the migration of control designers from .NET Framework to .NET might need to take a series of areas with breaking changes into account. The provided link points out additional resources which help in that migration process.
Relationship to .NET Framework
This codebase is a fork of the Windows Forms code in the .NET Framework 4.8.
We started the migration process by targeting .NET Core 3.0, when we’ve strived to bring the two runtimes to a parity. Since then, we’ve done a number of changes, including breaking changes, which diverged the two. For more information about breaking changes, see the Porting guide.
The bar for innovation and new features
WinForms is a technology which was originally introduced as a part of .NET Framework 1.0 on February 13th, 2002. It’s primary focus was and is to be a Rapid Application Tool for Windows based Apps, and that principal sentiment has not changed over the years. WinForms at the time addressed developer’s requests for
- A framework for stable, monolithic Line of Business Apps, even with extremely complicated and complex domain-specific workflows
- The ability to easily provide rich user interfaces
- A safe and — over the first 3 versions of .NET Framework — increasingly performant way to communicate across process boundaries via various Windows Communication Services, or access on-site databases via ADO.NET providers.
- A very easy to use, visual what-you-see-is-what-you-get designer, which requires little ramp-up time, and was primarily focused to support 96 DPI resolution-based, pixel-coordinated drag & drop design strategies.
- A flexible, .NET reflection-based Designer extensibility model, utilizing the .NET Component Model.
- Visual Controls and Components, which provide their own design-time functionality through Control Designers
Over time, and with a growing need to address working scenarios with multi-monitor, high resolution monitors, significantly more powerful hardware, and much more, WinForms has continued to be modernized.
And then there is the evolution of Windows: When new versions of Windows introduce new or change existing APIs or technologies — WinForms needs to keep up and adjust their APIs accordingly.
And exactly that is still the primary motivation for once to modernize and innovate, but also the bar to reach for potential innovation areas we either need or want to consider:
- Areas, where for example for security concerns, the Windows team needed to take an depending area out-of-proc, and we see and extreme performance hit in WinForms Apps running under a new Service Pack or a new Windows Version
- New features to comply with updated industry standards for accessibility.
- HighDPI and per Monitor V2-Scenarios.
- Picking up changed or extended Win32 Control functionality, to keep controls in WinForms working the way the Windows team wants them to be used.
- Addressing Performance and Security issues
- Introducing ways to support asynchronous calls interatively, to enable apps to pick up migration paths via Windows APIs projection/Windows Desktop Bridge, enable scenarios for async WebAPI, SignalR, Azure Function, etc. calls, so WinForms backends can modernized and even migrated to the cloud.
What would not make the bar:
- New functionality which modern Desktop UIs like WPF or WinUI clearly have already
- Functionality, which would «stretch» a Windows Desktop App to be a mobile, Multi-Media or IoT app.
- Domain-specific custom controls, which are already provided by the vast variety of third party control vendors
A note about Visual Basic: Visual Basic .NET developers make up about 20% of WinForms developers. We welcome changes that are specific to VB if they address a bug in a customer-facing scenario. Issues and PRs should describe the customer-facing scenario and, if possible, include images showing the problem before and after the proposed changes. Due to limited bandwidth, we cannot prioritize VB-specific changes that are solely for correctness or code cleanliness. However, VB remains important to us, and we aim to fix any critical issues that arise.
Please note
⚠️ This repository contains only implementations for Windows Forms for .NET platform.
It does not contain either:
- The .NET Framework variant of Windows Forms. Issues with .NET Framework, including Windows Forms, should be filed on the Developer Community or Product Support websites. They should not be filed on this repository.
- The Windows Forms Designer implementations. Issues with the Designer can be filed via VS Feedback tool (top right-hand side icon in Visual Studio) or be filed in this repo using the Windows Forms out-of-process designer issue template.
How can I contribute?
We welcome contributions! Many people all over the world have helped make this project better.
- Contributing explains what kinds of changes we welcome
- Developer Guide explains how to build and test
- Get Up and Running with Windows Forms .NET explains how to get started building Windows Forms applications.
How to Engage, Contribute, and Provide Feedback
Some of the best ways to contribute are to try things out, file bugs, join in design conversations, and fix issues.
- The contributing guidelines and the more general .NET contributing guide define contributing rules.
- The Developer Guide defines the setup and workflow for working on this repository.
- If you have a question or have found a bug, file an issue.
- Use daily builds if you want to contribute and stay up to date with the team.
Reporting security issues
Security issues and bugs should be reported privately via email to the Microsoft Security Response Center (MSRC) secure@microsoft.com. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Further information, including the MSRC PGP key, can be found in the Security TechCenter. Also see info about related Microsoft .NET Core and ASP.NET Core Bug Bounty Program.
Code of Conduct
This project uses the .NET Foundation Code of Conduct to define expected conduct in our community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer at conduct@dotnetfoundation.org.
License
.NET (including the Windows Forms repository) is licensed under the MIT license.
.NET Foundation
.NET Windows Forms is a .NET Foundation project.
See the .NET home repository to find other .NET-related projects.
From Wikipedia, the free encyclopedia
|
This article needs to be updated. Please help update this article to reflect recent events or newly available information. (January 2023) |
Windows Forms (WinForms)
Other names | WinForms |
---|---|
Original author(s) | .NET: Microsoft, Mono: Ximian/Novell |
Developer(s) | .NET Foundation |
Initial release | February 13, 2002; 23 years ago |
Stable release |
v8.0.0 |
Repository |
|
Written in | C# |
Operating system | Microsoft Windows |
Platform | .NET Framework, .NET, Mono |
Type | Software framework, widget toolkit |
License | MIT License |
Website | learn |
Windows Forms, also known as WinForms, is a free, open-source graphical user interface (GUI) class library for building Windows desktop applications, included as a part of Microsoft .NET, .NET Framework or Mono,[2] providing a platform to write client applications for desktop, laptop, and tablet PCs.[3] While it is seen as a replacement for the earlier and more complex C++ based Microsoft Foundation Class Library, it does not offer a comparable paradigm[4] and only acts as a platform for the user interface tier in a multi-tier solution.[5]
At the Microsoft Connect event on December 4, 2018, Microsoft announced releasing Windows Forms as an open source project on GitHub. It is released under the MIT License. With this release, Windows Forms has become available for projects targeting the .NET Core framework. However, the framework is still available only on the Windows platform, and Mono’s incomplete implementation of Windows Forms remains the only cross-platform implementation.[6][7]
A Windows Forms application is an event-driven application supported by Microsoft’s .NET Framework. Unlike a batch program, it spends most of its time simply waiting for the user to do something, such as fill in a text box or click a button. The code for the application can be written in a .NET programming language such as C# or Visual Basic.
Windows Forms provides access to native Windows User Interface Common Controls by wrapping the existent Windows API in managed code.[8] With the help of Windows Forms, the .NET Framework provides a more comprehensive abstraction above the Win32 API than Visual Basic or MFC did.[9]
Windows Forms is similar to Microsoft Foundation Class (MFC) library in developing client applications. It provides a wrapper consisting of a set of C++ classes for development of Windows applications. However, it does not provide a default application framework like the MFC. Every control in a Windows Forms application is a concrete instance of a class.
All visual elements in the Windows Forms class library derive from the Control class. This provides the minimal functionality of a user interface element such as location, size, color, font, text, as well as common events like click and drag/drop. The Control class also has docking support to let a control rearrange its position under its parent. The Microsoft Active Accessibility support in the Control class also helps impaired users to use Windows Forms better.[10]
In Visual Studio, forms are created using drag-and-drop techniques. A tool is used to place controls (e.g., text boxes, buttons, etc.) on the form (window). Controls have attributes and event handlers associated with them. Default values are provided when the control is created, but may be changed by the programmer. Many attribute values can be modified during run time based on user actions or changes in the environment, providing a dynamic application. For example, code can be inserted into the form resize event handler to reposition a control so that it remains centered on the form, expands to fill up the form, etc. By inserting code into the event handler for a keypress in a text box, the program can automatically translate the case of the text being entered, or even prevent certain characters from being inserted.
Besides providing access to native Windows controls like button, textbox, checkbox and listview, Windows Forms added its own controls for ActiveX hosting, layout arrangement, validation and rich data binding. Those controls are rendered using GDI+.[10]
Just like Abstract Window Toolkit (AWT), the equivalent Java API, Windows Forms was an early and easy way to provide graphical user interface components to the .NET Framework. Windows Forms is built on the existing Windows API and some controls merely wrap underlying Windows components.[11] Some of the methods allow direct access to Win32 callbacks, which are not available in non-Windows platforms.[11]
In .NET Framework 2.0, Windows Forms gained richer layout controls, Office 2003 style toolstrip controls, multithreading component, richer design-time and data binding support as well as ClickOnce for web-based deployment.[12][13]
With the release of .NET Framework 3.0, Microsoft released a second, parallel API for rendering GUIs: Windows Presentation Foundation (WPF) based on DirectX,[14] together with a GUI declarative language called XAML.[15]
During a question-and-answer session at the Build 2014 Conference, Microsoft explained that Windows Forms was under maintenance mode, with no new features being added, but bugs found would still be fixed.[16] Most recently, improved high-DPI support for various Windows Forms controls was introduced in updates to .NET Framework version 4.5.[17]
XAML backwards compatibility with Windows Forms
[edit]
For future development, Microsoft has succeeded Windows Forms with a XAML-based GUI entry using frameworks such as WPF and UWP. However, drag and drop placement of GUI components in a manner similar to Windows Forms is still provided in XAML by replacing the root XAML element of the Page/Window with a «Canvas» UI-Control. When making this change, the user can build a window in a similar fashion as in Windows Forms by directly dragging and dropping components using the Visual Studio GUI.
While XAML provides drag and drop placement backwards compatibility through the Canvas Control, XAML Controls are only similar to Windows Forms Controls and are not one-to-one backwards compatible. They perform similar functions and have a similar appearance, but the properties and methods are different enough to require remapping from one API to another.
Alternative implementation
[edit]
Mono is a project led by Xamarin (formerly by Ximian, then Novell) to create an Ecma standard compliant .NET Framework compatible set of tools.
In 2011, Mono’s support for System.Windows.Forms as of .NET 2.0 was announced as complete;[18]
System.Windows.Forms 2.0 works natively on Mac OS X.[19]
However, System.Windows.Forms has not been actively developed on Mono.[20]
Full compatibility with .NET was not possible, because Microsoft’s System.Windows Forms is mainly a wrapper around the Windows API, and some of the methods allow direct access to Win32 callbacks, which are not available in platforms other than Windows.[11]
A more significant problem is that, since version 5.2,[21]
Mono has been upgraded so that its default is to assume a 64 bit platform.
However, System.Windows.Forms on Mono for the Macintosh OS X platform has been built using a 32 bit subsystem, Carbon.[22]
As of this date[when?], a 64-bit version of System.Windows.Forms for use on Mac OS X remains unavailable and only .NET applications built for the 32 bit platform can be expected to execute.
- Microsoft Visual Studio
- ClickOnce
- Abstract Window Toolkit (AWT), the equivalent GUI application programming interface (API) for the Java programming language
- Visual Component Library (VCL) from Borland
- Visual Test, test automation
- ^ «v8.0.0». github.com. 2023-11-14. Retrieved 2023-11-21.
- ^ Sells, Chris (September 6, 2003). Windows Forms Programming in C# (1st ed.). Addison-Wesley Professional. p. xxxviiii.
- ^ «Design and Implementation Guidelines for Web Clients by Microsoft Pattern and Practices». Microsoft. November 2003.
- ^ Sells, Chris; Weinhardt, Michael (May 16, 2006). «Appendix B». Moving from MFC, Windows Forms 2.0 Programming (2nd ed.). Addison-Wesley Professional.
- ^ «Introduction to Windows Forms» (Visual Studio 2003 documentation). Microsoft 2003.
- ^ Martin, Jeff (4 December 2018). «Microsoft Open Sources WPF, WinForms, and WinUI». InfoQ. Retrieved 2018-12-06.
- ^ Hanselman, Scott (4 December 2018). «Announcing WPF, WinForms, and WinUI are going Open Source». Retrieved 2018-12-06.
- ^ De Smet, Bart (January 4, 2011). «Chapter 5». C# 4.0 Unleashed. Sams Publishing.
- ^ Griffiths, Ian; Adams, Matthew (March 2003). NET Windows Forms in a Nutshell. O’Reilly Media. p. 4.
- ^ a b Griffiths, Ian; Adams, Matthew (March 2003). NET Windows Forms in a Nutshell. O’Reilly Media. pp. 27–53.
- ^ a b c «FAQ: Winforms». mono-project.com.
It is very unlikely that the implementation will ever implement everything needed for full compatibility with Windows.Forms. The reason is that Windows.Forms is not a complete toolkit, and to work around this problem some of the underlying Win32 foundation is exposed to the programmer in the form of exposing the Windows message handler
- ^ Sells, Chris; Weinhardt, Michael (May 16, 2006). «Appendix A. What s New in Windows Forms 2.0». Windows Forms 2.0 Programming (2nd ed.). Addison-Wesley Professional.
- ^ Noyes, Brian (January 12, 2006). «Preface». Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET (1st ed.). Addison-Wesley Professional. ISBN 978-81-317-4823-7.
- ^ Hall, Gary (December 27, 2010). «DirectX, not GDI+». Pro WPF and Silverlight MVVM: Effective Application Development with Model (2010 ed.). Apress. p. 2.
- ^ Smith, Josh (2007-09-05). «WPF vs. Windows Forms». Josh Smith on WPF. Retrieved 2011-08-25.
WPF is not intended to replace Windows Forms. […] Windows Forms is still alive and well, and will continue to be enhanced and supported by Microsoft for years to come. WPF is simply another tool for Windows desktop application developers to use, when appropriate.
- ^ «A WPF Q&A». infoq.com. 2014-04-03. Retrieved 2014-04-21.
Windows Forms is continuing to be supported, but in maintenance mode. They will fix bugs as they are discovered, but new functionality is off the table
- ^ Allen, Jonathan (2014-05-06). «High DPI Improvements for Windows Forms in .NET 4.5.2». InfoQ. Retrieved 2015-02-10.
- ^ «WinForms». mono-project.com. Retrieved 2011-07-30.
Support for Windows Forms 2.0 is complete. At this point, we are largely just fixing bugs and polishing our code.
- ^ «WinForms». mono-project.com. Retrieved 2011-07-30.
Does Winforms run on OSX? Yes, as of Mono 1.9, Winforms has a native OSX driver that it uses by default
- ^ de Icaza, Miguel (2011-03-07). «GDC 2011». Retrieved 2011-07-30.
For tools that are mostly OpenGL/DirectX based, use Windows.Forms, keeping in mind that some bug fixing or work around on their part might be needed as our Windows.Forms is not actively developed.
- ^ «Introduction to Mono on macOS». mono-project.com. Retrieved 2019-11-12.
- ^ Martin, Jess. «Windows.Forms Comes to 64-bit Mac OS X». Retrieved 2019-11-12.
- MSDN: Building Windows Forms applications
- MSDN : Windows.Forms reference documentation
- MSDN : Windows Forms Technical Articles — Automating Windows Form with Visual Test
Last Updated :
25 Mar, 2025
Windows Forms (WinForms) is a GUI class library for building Windows desktop applications. Originally part of the .NET Framework, it is now supported in .NET Core, .NET 5+, .NET 8 (LTS), and .NET 9. Its main purpose is to provide an easier interface to develop applications for desktops, tablets, and PCs. It is also termed as the WinForms.
The applications developed using Windows Forms or WinForms are known as the Windows Forms Applications that run on the desktop computer. WinForms can be used only to develop Windows Forms Applications.
Creating First Windows Form
Let’s create the first Windows form here we are using Visual Studio Community 2022. Refer to this article which has a complete process on how to download Visual Studio.
Firstly we create a simple form that has a button and when we click on that button it shows a message let’s create it. These are the important steps to create a Windows form follow these steps as mentioned below:
Note: At the time of writing, Visual Studio Community 2022 is the latest stable version. However, check for newer versions like Visual Studio 2025 for updated features.
Step 1: Now open Visual Studio and different options are available there as of now.
Step 2: Now choose the Windows Forms App with C# and click on the next button.
Step 3: Now locate the project with the name here we are using the default name which is Form1 and it will open a form in the editor which we can further modify.
Let’s understand the interface of Visual Studio Community 2022 for Windows forms
- Editor Window (Main Window): Here, We will work with forms and code editing. Notice the layout of the form which is now blank. If we double-click the form then it will open the code for that.
- Solution Explorer: A file manager for your project where you can navigate between forms, resources, and settings. For example, if we will select a file from this window then particular information will be displayed in the property window.
- Properties Window: Allows you to modify UI elements such as colors, text alignment, and visibility. Also, we can change the properties of components or controls that will add to the forms.
In the image, we have two files that are open one Design and there is Form1.cs these two play a major role. We use the Form 1.cs file for the custom logic.
Step 4: Now open a Toolbox go to the view > Toolbox or ctrl + alt + x.
Toolbox: Provides drag-and-drop controls like buttons, text boxes, and labels to design the UI.
Step 5. Now open the common controls and drag and drop the button on the form where we want it to be placed.
Step 6. Now open the properties of the button press right-click on the button and it will open the properties solution explorer now we can change the button name to Click here.
Step 7: Now again open the Toolbox and then click on the label and place where we want to show the message.
Note: The Form1.Designer.cs file automatically generates UI code for Windows Forms. You should not manually edit this file, as changes may be lost. Instead, add event-handling logic in Form1.cs
Note: To handle user interactions, double-click a button to generate a Click event in Form1.cs. Here, you can define actions when the button is clicked.
Step 8. Now again double click on the button and it will open Form1.cs file and add the text when the button1 click action is triggered.
Form1.cs file:
C#
namespace WinFormsApp2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { label1.Text = "Hello Geeks!"; } } }
Step 9: Now click on the start button or press F5 to execute the program.
It will open a Windows form now to interact with the program.
Advantages
- Comprehensive Controls: It comes up with a rich set of customizable controls (buttons, text boxes labels etc.) that makes it easier to use and allows more control through properties and event handling
- Visual Designer: It comes up with the visual design helps to see the changes of form design and comes up with features like drag-and-drop for easy UI design.
- Code Integration: A specially designed code editor for forms design helps to write application logic, handling events and data validation.
- Use-cases: It is used in a variety of applications including the data entry tools, management system and business purposes.
- Easy and optimal: Always become a first choice to make a lightweight desktop application for rapid development and come up with .NET support.
From Wikibooks, open books for an open world
To create a Windows desktop application we use the library represented by System.Windows.Forms
namespace. Some commonly used classes in this namespace include:
- Control — generic class from which other useful classes, like
Form
,TextBox
and others listed below are derived - Form — this is the base class for the program window. All other controls are placed directly onto a
Form
or indirectly on another container (likeTabPage
orTabControl
) that ultimately resides on theForm
. When automatically created in Visual Studio, it is usually subclassed asForm1
. - Button — a clickable button
- TextBox — a singleline or multiline textbox that can be used for displaying or inputting text
- RichTextBox — an extended
TextBox
that can display styled text, e.g. with parts of the text colored or with a specified font. RichTextBox can also display generalized RTF document, including embedded images. - Label — simple control allowing display of a single line of unstyled text, often used for various captions and titles
- ListBox — control displaying multiple items (lines of text) with ability to select an item and to scroll through it
- ComboBox — similar to
ListBox
, but resembling a dropdown menu - TabControl and TabPage — used to group controls in a tabbed interface (much like tabbed interface in Visual Studio or Mozilla Firefox). A
TabControl
contains a collection ofTabPage
objects. - DataGrid — data grid/table view
The Form
class (System.Windows.Forms.Form) is a particularly important part of that namespace because the form is the key graphical building block of Windows applications. It provides the visual frame that holds buttons, menus, icons, and title bars together. Integrated development environments (IDEs) like Visual C# and SharpDevelop can help create graphical applications, but it is important to know how to do so manually:
using System.Windows.Forms; public class ExampleForm : Form // inherits from System.Windows.Forms.Form { public static void Main() { ExampleForm wikibooksForm = new ExampleForm(); wikibooksForm.Text = "I Love Wikibooks"; // specify title of the form wikibooksForm.Width = 400; // width of the window in pixels wikibooksForm.Height = 300; // height in pixels Application.Run(wikibooksForm); // display the form } }
The example above creates a simple Window with the text «I Love Wikibooks» in the title bar. Custom form classes like the example above inherit from the System.Windows.Forms.Form
class. Setting any of the properties Text
, Width
, and Height
is optional. Your program will compile and run successfully, if you comment these lines out, but they allow us to add extra control to our form.
|
This section is a stub. You can help Wikibooks by expanding it. |
An event is an action being taken by the program when a user or the computer makes an action (for example, a button is clicked, a mouse rolls over an image, etc.). An event handler is an object that determines what action should be taken when an event is triggered.
using System.Windows.Forms; using System.Drawing; public class ExampleForm : Form // inherits from System.Windows.Forms.Form { public ExampleForm() { this.Text = "I Love Wikibooks"; // specify title of the form this.Width = 300; // width of the window in pixels this.Height = 300; // height in pixels Button HelloButton = new Button(); HelloButton.Location = new Point(20, 20); // the location of button in pixels HelloButton.Size = new Size(100, 30); // the size of button in pixels HelloButton.Text = "Click me!"; // the text of button // When clicking the button, this event fires HelloButton.Click += new System.EventHandler(WhenHelloButtonClick); this.Controls.Add(HelloButton); } void WhenHelloButtonClick(object sender, System.EventArgs e) { MessageBox.Show("You clicked! Press OK to exit this message"); } public static void Main() { Application.Run(new ExampleForm()); // display the form } }
|
This section is a stub. You can help Wikibooks by expanding it. |
The Windows Forms namespace has a lot of very interesting classes. One of the simplest and important is the Form
class. A form is the key building block of any Windows application. It provides the visual frame that holds buttons, menus, icons and title bars together. Forms can be modal and modalless, owners and owned, parents and children. While forms could be created with a notepad, using a form editor like VS.NET, C# Builder or Sharp Develop makes development much faster. In this lesson, we will not be using an IDE. Instead, save the code below into a text file and compile with command line compiler.
using System.Windows.Forms; using System.Drawing; public class ExampleForm : Form // inherits from System.Windows.Forms.Form { public ExampleForm() { this.Text = "I Love Wikibooks"; // specify title of the form this.BackColor = Color.White; this.Width = 300; // width of the window in pixels this.Height = 300; // height in pixels // A Label Label TextLabel = new Label(); TextLabel.Text = "One Label here!"; TextLabel.Location = new Point(20, 20); TextLabel.Size = new Size(150, 30); TextLabel.Font = new Font("Arial", 12); // See! we can modify the font of text this.Controls.Add(TextLabel); // adding the control to the form // A input text field TextBox Box = new TextBox(); // inherits from Control Box.Location = new Point(20, 60); // then, it have Size and Location properties Box.Size = new Size(100, 30); this.Controls.Add(Box); // all class that inherit from Control can be added in a form } public static void Main() { Application.EnableVisualStyles(); Application.Run(new ExampleForm()); // display the form } }
В этом обзоре рассматриваются преимущества интеллектуальных клиентских приложений, основные возможности программирования Windows Forms, а также использование Windows Forms для разработки интеллектуальных клиентов, удовлетворяющих запросам современных предприятий и конечных пользователей.
Windows Forms и интеллектуальные клиентские приложения
Windows Forms позволяет разрабатывать интеллектуальные клиенты. Интеллектуальный клиент — это приложение с полнофункциональным графическим интерфейсом, простое в развертывании и обновлении, способное работать при наличии или отсутствии подключения к Интернету и использующее более безопасный доступ к ресурсам на локальном компьютере по сравнению с традиционными приложениями Windows.
Создание интерактивных пользовательских интерфейсов
Windows Forms — это технология разработки интеллектуальных клиентов для .NET Framework. Она представляет собой набор управляемых библиотек, упрощающих выполнение стандартных задач, таких как чтение из файловой системы и запись в нее. При использовании среды разработки, например Visual Studio, можно создавать приложения интеллектуальных клиентов Windows Forms, которые отображают информацию, запрашивают ввод от пользователей и взаимодействуют с удаленными компьютерами по сети.
Форма в Windows Forms — это визуальная поверхность, на которой выводится информация для пользователя. Обычно приложение Windows Forms строится путем помещения элементов управления на форму и написания кода для реагирования на действия пользователя, такие как щелчки мыши или нажатия клавиш. Элемент управления — это отдельный элемент пользовательского интерфейса, предназначенный для отображения или ввода данных.
При выполнении пользователем какого-либо действия с формой или одним из ее элементов управления создается событие. Приложение реагирует на эти события с помощью кода и обрабатывает события при их возникновении. Подробнее см. в разделе Создание обработчиков событий в Windows Forms.
Windows Forms включает широкий набор элементов управления, которые можно добавлять на формы: текстовые поля, кнопки, раскрывающиеся списки, переключатели и даже веб-страницы. Список всех элементов управления, которые можно использовать на форме, представлены в разделе Элементы управления для использования в формах Windows Forms. Если существующий элемент управления не удовлетворяет потребностям, в Windows Forms можно создать пользовательские элементы управления с помощью класса UserControl.
В состав Windows Forms входят многофункциональные элементы пользовательского интерфейса, позволяющие воссоздавать возможности таких сложных приложений, как Microsoft Office. Используя элементы управления ToolStrip и MenuStrip, можно создавать панели инструментов и меню, содержащие текст и рисунки, подменю и другие элементы управления, такие как текстовые поля и поля со списками.
С помощью Visual Studio и конструктора Windows Forms, можно легко создавать приложения Windows Forms путем перетаскивания элементов на формы. Достаточно выделить элемент управления курсором и поместить его в нужное место на форме. Для преодоления трудностей, связанных с выравниванием элементов управления, конструктор предоставляет такие средства, как линии сетки и линии привязки. С помощью Visual Studio или компиляции из командной строки, можно использовать элементы управления FlowLayoutPanel, TableLayoutPanel и SplitContainer для создания сложных макетов форм за короткое время.
Наконец, если нужно создать свои собственные элементы пользовательского интерфейса, пространство имен System.Drawing содержит широкий набор классов, необходимых для отрисовки линий, кругов и других фигур непосредственно на форме.
Note
Элементы управления Windows Forms не предназначены для маршалинга между доменами приложений. По этой причине технологии Майкрософт не поддерживают передачу элементов управления Windows Forms через границы AppDomain, хотя на первый взгляд базовый тип Control, класс MarshalByRefObject, подразумевает такую возможность. Приложения Windows Forms с несколькими доменами приложений поддерживаются только при условии, что элементы управления Windows Forms не передаются через границы доменов приложения.
Создание форм и элементов управления
Пошаговые инструкции по использованию этих возможностей можно найти в приведенных ниже разделах справки.
Описание | Раздел справки |
---|---|
Использование элементов управления в формах | Практическое руководство. Добавление элементов управления Windows Forms |
Использование элемента управления ToolStrip | Практическое руководство. Создание базового элемента управления ToolStrip со стандартными элементами с помощью конструктора |
Создание графических элементов с помощью System.Drawing | Приступая к программированию графики |
Создание пользовательских элементов управления | Практическое руководство. Наследование класса UserControl |
Отображение данных и управление ими
Во многих приложениях нужно отображать данные из базы данных, XML-файла, веб-службы XML или другого источника данных. Windows Forms предоставляет гибкий элемент управления с именем DataGridView для отображения таких табличных данных в традиционном формате строк и столбцов так, что каждый фрагмент данных занимает свою собственную ячейку. С помощью DataGridView можно, помимо прочего, настроить внешний вид отдельных ячеек, зафиксировать строки и столбцы на своем месте, а также обеспечить отображение сложных элементов управления внутри ячеек.
При использовании интеллектуальных клиентов Windows Forms можно легко подключаться к источникам данных по сети. Компонент BindingSource представляет собой соединение с источником данных и предоставляет методы для привязки данных к элементам управления, перехода к предыдущей и последующей записи, редактирования записей и сохранения изменений обратно в исходный источник. Элемент управления BindingNavigator предоставляет простой интерфейс на основе компонента BindingSource для перехода между записями.
Вы можете легко создавать элементы управления с привязкой к данным с помощью окна «Источники данных». В нем приводятся имеющиеся в проекте источники данных, такие как базы данных, веб-службы и объекты. Создавать элементы управления с привязкой к данным можно путем перетаскивания объектов из этого окна в формы проекта. Также можно связывать существующие элементы управления с данными, перетаскивая объекты из окна «Источники данных» в существующие элементы управления.
Другой тип привязки к данным в формах Windows Forms — это параметры. Большинство интеллектуальных клиентских приложений должны сохранять некоторые сведения о своем состоянии во время выполнения, такие как последние известные размеры форм, а также сохранять пользовательские предпочтения, например место сохранения файлов по умолчанию. Параметры приложения отвечает этим требованиям, предоставляя простой способ хранения обоих типов сведений на клиентском компьютере. После определения этих параметров с помощью Visual Studio или редактора кода, значения параметров сохраняются в XML и автоматически считываются обратно в память во время выполнения.
Отображение данных и управление ими
Пошаговые инструкции по использованию этих возможностей можно найти в приведенных ниже разделах справки.
Описание | Раздел справки |
---|---|
Использование компонента BindingSource | Практическое руководство. Привязка элементов управления Windows Forms с компонентом BindingSource с помощью конструктора |
Работа с источниками данных ADO.NET | Практическое руководство. Сортировка и фильтрация данных ADO.NET с помощью Windows Forms посредством компонента BindingSource |
Использование окна «Источники данных» | Привязка элементов управления Windows Forms к данным в Visual Studio |
Использование параметров приложения | Практическое руководство. Создание параметров приложения |
Развертывание приложений на клиентских компьютерах
После создания приложения необходимо отправить его пользователям, чтобы они могли установить и запустить его на своих клиентских компьютерах. При использовании технологии ClickOnce, можно развернуть приложения в Visual Studio с помощью нескольких щелчков и предоставить пользователям URL-адрес приложения в Интернете. ClickOnce управляет всеми элементами и зависимостями в приложении и обеспечивает его правильную установку на клиентском компьютере.
Приложения ClickOnce можно настроить так, чтобы они работали либо только при подключении к сети, либо как в сетевом, так и в автономном режиме. Если вы указываете, что приложение должно поддерживать работу в автономном режиме, то технология ClickOnce добавляет ссылку на приложение в меню Пуск пользователя. Пользователь может открыть приложение без использования URL-адреса.
Когда вы обновляете приложение, на веб-сервере публикуется новый манифест развертывания и новая копия приложения. ClickOnce обнаруживает доступное обновление и обновляет пользовательскую установку. Для обновления старых сборок написание специального кода не требуется.
Развертывание приложений ClickOnce
Общие сведения о ClickOnce можно найти в разделе Развертывание и безопасность технологии ClickOnce. Пошаговые инструкции по использованию этих возможностей можно найти в приведенных ниже разделах справки.
Описание | Раздел справки |
---|---|
Развертывание приложения с помощью ClickOnce | Практическое руководство. Публикация приложения ClickOnce с помощью мастера публикации
Пошаговое руководство: Развертывание вручную приложения ClickOnce |
Обновление приложений при развертывании через ClickOnce | Практическое руководство. Управление обновлениями для ClickOnce-приложения |
Управление безопасностью в ClickOnce | Практическое руководство. Включение параметров безопасности ClickOnce-приложений |
Другие элементы управления и функции
В Windows Forms имеется множество других возможностей, которые упрощают и ускоряют реализацию распространных задач, таких как создание диалоговых окон, печать, добавление справки и документации, а также локализация приложений на различных языках. Кроме того, в Windows Forms применяется эффективная система безопасности .NET Framework. Благодаря ей можно создавать более надежные приложения.
Реализации других элементов управления и компонентов
Пошаговые инструкции по использованию этих возможностей можно найти в приведенных ниже разделах справки.
Описание | Раздел справки |
---|---|
Печать содержимого формы | Практическое руководство. Печать графических изображений в Windows Forms
Практическое руководство. Печать многостраничных текстовых файлов в Windows Forms |
Дополнительные сведения о безопасности в Windows Forms | Общие сведения о безопасности в Windows Forms |
См. также
- Приступая к работе с Windows Forms
- Создание новой формы Windows Forms
- Общие сведения об элементе управления ToolStrip
- Общие сведения об элементе управления DataGridView
- Общие сведения о компоненте BindingSource
- Общие сведения о параметрах приложений
- Развертывание и безопасность технологии ClickOnce