Introduction
Windows Forms (WinForms) provides a rich set of managed UI components for building desktop applications with the Visual Basic .NET language. This documentation covers the core concepts, common controls, event handling, layout strategies, and best practices.
Getting Started
Create a new Windows Forms project in Visual Studio using the VB Windows Forms App
template. The IDE generates a Form1.vb
class that inherits from System.Windows.Forms.Form
.
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Text = "Hello, Windows Forms!"
End Sub
End Class
This simple form displays a title bar with the text Hello, Windows Forms!.
Key Concepts
- Controls: Visual elements like
Button
,TextBox
,Label
, etc. - Events: User interactions (click, key press) are exposed as events you can handle.
- Layout: Use containers such as
TableLayoutPanel
orFlowLayoutPanel
for responsive designs. - Data Binding: Bind controls to data sources for automatic UI updates.
Sample Application
The following example demonstrates a basic calculator with two input fields, a button, and a label that displays the result.
Public Class CalculatorForm
Inherits Form
Private txtA As New TextBox() With {.Location = New Point(20, 20), .Width = 80}
Private txtB As New TextBox() With {.Location = New Point(110, 20), .Width = 80}
Private btnAdd As New Button() With {.Text = "Add", .Location = New Point(200, 18)}
Private lblResult As New Label() With {.AutoSize = True, .Location = New Point(20, 60)}
Public Sub New()
Text = "Simple Calculator"
Controls.AddRange({txtA, txtB, btnAdd, lblResult})
AddHandler btnAdd.Click, AddressOf OnAddClicked
End Sub
Private Sub OnAddClicked(sender As Object, e As EventArgs)
Dim a, b As Double
If Double.TryParse(txtA.Text, a) AndAlso Double.TryParse(txtB.Text, b) Then
lblResult.Text = $"Result: {a + b}"
Else
lblResult.Text = "Invalid input."
End If
End Sub
End Class
Module Program
Sub Main()
Application.EnableVisualStyles()
Application.Run(New CalculatorForm())
End Sub
End Module