In this short tutorial, you'll learn how to create a new Windows Forms app with Visual Studio. Once the initial app has been generated, you'll learn how to add controls and how to handle events. By the end of this tutorial, you'll have a simple app that adds names to a list box.
In this tutorial, you learn how to:
Use Visual Studio 2022 version 17.4 or later and install both the .NET 7 and .NET 6 individual components. Support for .NET 7 was added in Visual Studio 2022 version 17.4.
The first step to creating a new app is opening Visual Studio and generating the app from a template.
The following image shows both C# and Visual Basic .NET project templates. If you applied the code language filter, you'll see the corresponding template.
The following image shows both C# and Visual Basic .NET project templates. If you applied the code language filter, you'll see the corresponding template.
Once the app is generated, Visual Studio should open the designer pane for the default form, Form1. If the form designer isn't visible, double-click on the form in the Solution Explorer pane to open the designer window.
Support for Windows Forms in Visual Studio has four important components that you'll interact with as you create an app:
If the toolbox isn't visible, you can display it through the View > Toolbox menu item.
With the Form1 form designer open, use the Toolbox pane to add the following controls to the form:
You can position and size the controls according to the following settings. Either visually move them to match the screenshot that follows, or click on each control and configure the settings in the Properties pane. You can also click on the form title area to select the form:
Object | Setting | Value |
---|---|---|
Form | Text | Names |
Size | 268, 180 | |
Label | Location | 12, 9 |
Text | Names | |
Listbox | Name | lstNames |
Location | 12, 27 | |
Size | 120, 94 | |
Textbox | Name | txtName |
Location | 138, 26 | |
Size | 100, 23 | |
Button | Name | btnAdd |
Location | 138, 55 | |
Size | 100, 23 | |
Text | Add Name |
You should have a form in the designer that looks similar to the following:
Now that the form has all of its controls laid out, you need to handle the events of the controls to respond to user input. With the form designer still open, perform the following steps:
private void btnAdd_Click(object sender, EventArgs e)
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click End Sub
private void btnAdd_Click(object sender, EventArgs e)
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click If Not String.IsNullOrWhiteSpace(txtName.Text) And Not lstNames.Items.Contains(txtName.Text) Then lstNames.Items.Add(txtName.Text) End If End Sub
Now that the event has been coded, you can run the app by pressing the F5 key or by selecting Debug > Start Debugging from the menu. The form displays and you can enter a name in the textbox and then add it by clicking the button.