Последнее обновление: 25.11.2023
-
Глава 1. Введение в Windows Forms
-
Первое приложение с .NET CLI
-
Первое приложение в Visual Studio
-
Создание графического приложения
-
-
Глава 2. Работа с формами
-
Основы форм
-
Основные свойства форм
-
Добавление форм. Взаимодействие между формами
-
События в Windows Forms. События формы
-
Создание непрямоугольных форм. Закрытие формы
-
-
Глава 3. Контейнеры в Windows Forms
-
Динамическое добавление элементов
-
Элементы GroupBox, Panel и FlowLayoutPanel
-
TableLayoutPanel
-
Размеры элементов и их позиционирование в контейнере
-
Панель вкладок TabControl и SplitContainer
-
-
Глава 4. Элементы управления
-
Кнопка
-
Метки и ссылки
-
Текстовое поле TextBox
-
Элемент MaskedTextBox
-
Элементы Radiobutton и CheckBox
-
ListBox
-
Элемент ComboBox
-
Привязка данных в ListBox и ComboBox
-
Элемент CheckedListBox
-
Элементы NumericUpDown и DomainUpDown
-
ImageList
-
ListView
-
TreeView
-
TrackBar, Timer и ProgressBar
-
DateTimePicker и MonthCalendar
-
PictureBox
-
WebBrowser
-
Элемент NotifyIcon
-
Окно сообщения MessageBox
-
OpenFileDialog и SaveFileDialog
-
FontDialog и ColorDialog
-
ErrorProvider
-
-
Глава 5. Меню и панели инструментов
-
Панель инструментов ToolStrip
-
Создание меню MenuStrip
-
Строка состояния StatusStrip
-
Контекстное меню ContextMenuStrip
-
-
Глава 6. Привязка и паттерн Model-View-ViewModel
-
Введение в привязку. Форматирование значения привязки
-
Привязка объектов. Интерфейс INotifyPropertyChanged
-
DataContext
-
Паттерн Model-View-ViewModel
-
Команды и взаимодействие с пользователем в MVVM
-
Параметры команды
-
- Глава 1. Введение в Windows Forms
- Первое приложение с .NET CLI
- Первое приложение в Visual Studio
- Создание графического приложения
- Глава 2. Работа с формами
- Основы форм
- Основные свойства форм
- Добавление форм. Взаимодействие между формами
- События в Windows Forms. События формы
- Создание непрямоугольных форм. Закрытие формы
- Глава 3. Контейнеры в Windows Forms
- Динамическое добавление элементов
- Элементы GroupBox, Panel и FlowLayoutPanel
- TableLayoutPanel
- Размеры элементов и их позиционирование в контейнере
- Панель вкладок TabControl и SplitContainer
- Глава 4. Элементы управления
- Кнопка
- Метки и ссылки
- Текстовое поле TextBox
- Элемент MaskedTextBox
- Элементы Radiobutton и CheckBox
- ListBox
- Элемент ComboBox
- Привязка данных в ListBox и ComboBox
- Элемент CheckedListBox
- Элементы NumericUpDown и DomainUpDown
- ImageList
- ListView
- TreeView
- TrackBar, Timer и ProgressBar
- DateTimePicker и MonthCalendar
- PictureBox
- WebBrowser
- Элемент NotifyIcon
- Окно сообщения MessageBox
- OpenFileDialog и SaveFileDialog
- FontDialog и ColorDialog
- ErrorProvider
- Глава 5. Меню и панели инструментов
- Панель инструментов ToolStrip
- Создание меню MenuStrip
- Строка состояния StatusStrip
- Контекстное меню ContextMenuStrip
- Глава 6. Привязка и паттерн Model-View-ViewModel
- Введение в привязку. Форматирование значения привязки
- Привязка объектов. Интерфейс INotifyPropertyChanged
- DataContext
- Паттерн Model-View-ViewModel
- Команды и взаимодействие с пользователем в MVVM
- Параметры команды
Помощь сайту
Номер карты:
4048415020898850
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Appearance settings
Prerequisites
- Visual Studio 2022
- TX Text Control .NET for Windows Forms
Step 1: Create a New Project
- Open Visual Studio 2022.
- Click on «Create a new project».
- From the options, select C# under Languages, Windows under Platform, and Desktop under Project Type.
- Scroll to find the Windows Forms App template.
- Select it and click Next.
Step 2: Name Your Project and Choose the Framework
- Enter a project name and click Next.
- Select your Framework version as .NET 6 (Long-term support) and click Create.
Step 3: Install the Required NuGet Package
- Right-click the project in Solution Explorer.
- Select Manage NuGet Packages from the context menu.
- Choose Text Control Offline Packages as the package source, then click Browse.
- Find TXTextControl.TextControl.WinForms.SDK and click Install.
Step 4: Add the Text Control to Your Form
- In Solution Explorer, open Form1.
- In the Toolbox, find the TX Text Control 32.0 tab.
- Select the TextControl icon and draw it onto the Windows form.
Step 5: Customize the Text Control
- Click the Smart Tag in the upper right corner of TextControl.
- In the Wizards group, click on:
- Add a Button Bar
- Add a Status Bar
- Add a Ruler
- Add a Vertical Ruler
- Finally, click Arrange Controls Automatically.
The controls will now be connected and docked to fill the container.
Step 6: Build and Compile
- Click the Start button to build and compile the project.
- The application will start and the Text Control will be displayed on the form.
Conclusion
In this tutorial, you learned how to create a new Windows Forms application in Visual Studio 2022 and how to add a Text Control to the form. You also learned how to customize the Text Control by adding a Button Bar, Status Bar, Ruler, and Vertical Ruler. Finally, you built and compiled the project to see the Text Control in action.
Windows Forms
Text Control combines the power of a reporting tool and an easy-to-use WYSIWYG word processor — fully programmable and embeddable in your Windows Forms application. TX Text Control .NET for Windows Forms is a royalty-free, fully programmable rich edit control that offers developers a broad range of word processing features in a reusable component for Visual Studio.
See Windows Forms products
Related Posts
Getting Started with Windows Forms (.NET Framework)
by Bjoern Meyer| September 1, 2022
This article shows how to use the TX Text Control .NET for Windows Forms TextControl class within a .NET Framework (4.8) application in Visual Studio 2022.
Getting Started with Windows Forms (.NET 5 and better)
by Bjoern Meyer| September 1, 2022
This article shows how to use the TX Text Control .NET for Windows Forms TextControl class within a .NET 6 application in Visual Studio 2022.
New Getting Started Article Hub Launched
by Bjoern Meyer| July 11, 2022
We just launched a new getting started article hub that helps to find articles, samples, and tutorials by filtering by types, technologies and Text Control components.
Creating Your First Windows Forms Application with C#
by Bjoern Meyer| January 1, 2020
This Windows Forms tutorial shows how to create your first desktop application with C# using TX Text Control .NET for Windows Forms.
Windows Forms is a framework available in Visual Studio that allows you to build desktop applications with the assistance of a graphical user interface. This allows you to click and drag widgets such as buttons or labels directly onto a canvas, and manipulate the properties of each widget such as its font-size, color or border.
In this article, a simple Celsius to Fahrenheit Converter will be used as an example to go through the basics of how to set up a Windows Form Application. Visual Studio 2019 Community Edition is the edition used for this tutorial.
How to Create the Windows Forms Project in Visual Studio
First, create the project in Visual Studio.
- Open Visual Studio and select Create a New Project.
- Visual Studio will provide you with a list of project templates you can choose from.
-
To create a Windows Forms Application, search for Windows Form App and select it from the list of templates. Once this is selected, click on Next.
If the Windows Form App option is not available on the list, modify your installed version of Visual Studio. In Visual Studio Installer, add the .NET desktop development workload for Desktop and Mobile, and re-launch Visual Studio.
-
Add a name and location for the project, and click on Next. The location is the directory where the code files will be stored.
- On the next screen, keep the default selection of .NET Core 3.1.
-
Click Create.
-
Once Visual Studio has finished creating the project, the project will open.
How to Add Elements to the Project Canvas
The canvas is the white area located at the top-left of the screen. Click and drag the points on the bottom, right, or bottom-right of the canvas to resize it if needed.
To create the UI of the application, add widgets such as buttons or text boxes onto the canvas.
-
Open the View Tab at the top of the window, and select Toolbox.
- This will add a toolbox to the left side of the application. Select the pin icon in the top-right of the toolbox to pin it there permanently.
-
This is where you can drag any widget from the toolbox onto the canvas. Highlight a button from the toolbox, and drag it onto the canvas.
-
Drag two more text boxes onto the canvas, along with three labels (two labels for each text box, and one label for the title at the top of the application).
- Every widget on the canvas has properties associated with them. Highlight a widget to display the Properties window in the bottom-right of Visual Studio, which lists all the properties that widget has. These properties can include the text, name, font size, border, or alignment of the highlighted widget.
-
At the moment, the text on these widgets still say label1, label2, or button1. Select the label1 widget and edit the Text property in the properties window to say «Celsius to Fahrenheit». Change the font size to be 22pt.
-
Similarly, edit the properties of the other widgets on the canvas to be the following:
Widget
Property
New Value
label2
Text
Celsius
label3
Text
Fahrenheit
button
Text
Calculate
Fahrenheit text box
ReadOnly
True
How to Handle Events and Write Code in the Code-Behind
Widgets on the canvas can be tied to events. Events can include things like clicking on a button, changing the text inside a text box, or selecting a particular radio button. When these events happen, it can cause a section of code in the Code-Behind to trigger.
C# is the language used when creating Windows Forms. If you haven’t already used C#, there are many practical reasons to learn C# programming.
For this particular application, add an event to the Calculate button, to trigger a section of code to run when this button is pressed.
-
Double-click the Calculate button to automatically open Form1.cs with a new Event method:
private void calculateButton_Click(object sender, EventArgs e)
- This is where you will add the code that will perform the Celsius to Fahrenheit calculation, and display the result in the Fahrenheit text box. To do this, you need to be able to read the value from the Celsius text box, and modify the Fahrenheit text box to display the result.
-
Go back to the canvas, and re-edit the properties as shown before. This time, edit the Name property for both the Celsius and Fahrenheit text boxes. These names can be used to reference the text boxes in the code.
Widget
Property
New Value
Celsius Text Box
Name
celsiusTextBox
Fahrenheit Text Box
Name
fahrenheitTextBox
- Go back to the calculateButton_Click function in Form1.cs.
-
Now, the Celsius text box can be referred to in the code using the name «celsiusTextBox». The Celsius value the user entered is stored in its Text property. However, since it’s a string, parse this into a double in order to include it in the future Fahrenheit calculations.
private void calculateButton_Click(object sender, EventArgs e)
{
// Get the value that the user entered in the Celsius Text Box
double celsiusValue = Double.Parse(celsiusTextBox.Text);
} -
The celsiusValue variable now stores the value that the user entered in the Celsius Text Box. The formula for converting Celsius to Fahrenheit is (celsiusValue * 9 / 5) + 32. Therefore, the result can now be calculated and stored in the Fahrenheit Text Box.
private void calculateButton_Click(object sender, EventArgs e)
{
// Get the value that the user entered in the Celsius Text Box
double celsiusValue = Double.Parse(celsiusTextBox.Text);// Apply the calculation
double result = (celsiusValue * 9 / 5) + 32;// Store the result in the Fahrenheit Textbox
fahrenheitTextBox.Text = result.ToString();
}
How to Run and Debug the Windows Forms Program
Running the Windows Forms Program in Visual Studio
Now that the UI and code logic is set up, run the program to see it working.
-
To run the program, select the green arrow at the top of the toolbar in Visual Studio.
-
Once the project has loaded, add a value into the Celsius text box and press the Calculate button. This will add the result into the Fahrenheit text box.
- If the program is blurry at runtime, it is likely your application is not DPI aware. This can cause scaling and resolution issues, so this will need to be enabled. You can also read more about configuring display scaling on Windows 10 for High-DPI monitors.
- Right-click on the TemperatureConverter Project in the Solutions Explorer. Select Add, then select New Item.
-
Search for the Application Manifest File, and click Add.
-
Copy the following code into the new app.manifest file, as a child of the assembly tag (if the code is already generated, just un-comment it).
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application> - For this change to take effect, re-run the program. Select the red stop button at the top of the toolbar, then select the green play button again.
Debugging the Windows Forms Program
You may want to debug the program if the logic of your Windows Forms application is not working as expected.
- Navigate back to the calculateButton_Click function in Form1.cs and click anywhere on the gray bar in the far-left of the screen. This will add a breakpoint, which is indicated by a red circle.
- Press the «Calculate» button again to trigger this method to execute. The program will pause when it hits the breakpoint to show all the values stored in the variables at that point.
-
To continue the program, click the green Continue arrow at the top of the toolbar.
Running the Program Using an Executable File
If you don’t want to run your program through Visual Studio, use the standalone executable file for the program. This is automatically generated.
-
Navigate to the executable file, which can be found here:
<your-project-folder>/bin/Debug/netcoreapp3.1/TemperatureConverter.exe
- Click on the executable file to directly run the program.
Adding More to Your Windows Form
Hopefully you now have a basic understanding of the basic structure of a Windows Form Application. You can continue exploring additional Windows Forms features by experimenting with new widgets, and taking a deeper dive into the other various events that can be handled.
Once you are more familiar with Windows Forms, you can start creating more complex applications. You can also explore many of the other ways you can create applications on Windows desktop.