WinForms event model
WinForms event model
WinForms builds a Windows desktop UI from controls and event handlers. A user action raises an event; a handler reads input, invokes application logic and updates the view. Keep the validation rule independent of the Form so the rule is easy to test.
A Form owns controls and has a lifetime connected to the Windows message loop. Button.Click signals activation, including keyboard activation; TextChanged can run for programmatic updates too. Use layout panels, AutoSize and tab order instead of relying on pixel-perfect positioning. Event handlers can call a presenter or domain service; return validation results rather than throwing for routine invalid input. A long-running operation must not block the UI thread. If a form subscribes to an external longer-lived publisher, detach handlers when the form closes. Controls owned by the form are disposed with it. Distinguish an in-memory preview from a durable inventory write; repeated clicks must not silently duplicate a durable operation. The examples deliberately use only synthetic data.
Baseline: .NET 10 / C# 14. Every expected result is reasoned, not executed. The complete portable and Windows desktop projects are separate from MAUI template overlays. No runtime or UI claims.
Handle a button activation
Type empty text and press Add, then enter Atlas and press Enter.
Use an approved Windows .NET 10 environment. Build the complete Fixture.csproj after approved restore; run it and close the window when finished.
using System;using System.Drawing;using System.Windows.Forms;using System.Threading.Tasks;namespace Fixture;public static class Program { [STAThread] public static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new InventoryForm()); }}public sealed class InventoryForm : Form { public InventoryForm() { Text="Inventory entry"; AutoScaleMode=AutoScaleMode.Font; ClientSize=new Size(420,220); var name=new TextBox { Width=230, AccessibleName="Item name", TabIndex=0 }; var add=new Button { Text="&Add", AutoSize=true, TabIndex=1 }; var status=new Label { AutoSize=true, Text="Enter an item" }; var layout=new FlowLayoutPanel { Dock=DockStyle.Fill, FlowDirection=FlowDirection.TopDown, Padding=new Padding(12), WrapContents=false, AutoScroll=true }; layout.Controls.AddRange(new Control[]{new Label {Text="Item name",AutoSize=true},name,add,status}); Controls.Add(layout); AcceptButton=add; add.Click += (_,_) => { var value=name.Text.Trim(); status.Text=value.Length==0?"Name required":$"Preview: {value}"; }; }}Expected result (not executed):
Empty: Name required. Atlas: Preview: Atlas.Click delegates one small action to a validation rule; AcceptButton provides an Enter-key path.
React to text changes
Type 0, then 3, then letters; observe the availability of Preview.
Use an approved Windows .NET 10 environment. Build the complete Fixture.csproj after approved restore; run it and close the window when finished.
using System;using System.Drawing;using System.Windows.Forms;using System.Threading.Tasks;namespace Fixture;public static class Program { [STAThread] public static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new InventoryForm()); }}public sealed class InventoryForm : Form { public InventoryForm() { Text="Quantity preview"; ClientSize=new Size(420,220); AutoScaleMode=AutoScaleMode.Font; var quantity=new TextBox { AccessibleName="Quantity", TabIndex=0, Width=140 }; var preview=new Button { Text="&Preview", Enabled=false, AutoSize=true, TabIndex=1 }; var status=new Label { Text="Enter 1 to 20", AutoSize=true }; var panel=new FlowLayoutPanel { Dock=DockStyle.Fill, FlowDirection=FlowDirection.TopDown, WrapContents=false, Padding=new Padding(12), AutoScroll=true }; panel.Controls.AddRange(new Control[]{new Label { Text="Quantity",AutoSize=true },quantity,preview,status}); Controls.Add(panel); quantity.TextChanged += (_,_) => preview.Enabled=IsValid(); preview.Click += (_,_) => status.Text=IsValid()?"Quantity accepted":"Invalid quantity"; bool IsValid() => int.TryParse(quantity.Text,out int n) && n is >=1 and <=20; }}Expected result (not executed):
0: disabled; 3: enabled; letters: disabled.TextChanged updates affordances, but the click handler also validates. Production input rules may require explicit culture.
Test presenter outcomes without a Form
Use a separate validation function for the event handler.
Use the complete Fixture.csproj with an approved .NET 10 SDK. Restore approved dependencies, build and run. No UI workload needed.
using System;foreach(var raw in new[]{"", " Atlas ", "abcdefghijklmnopqrstuvwxyz"}) { var result=Preview(raw); Console.WriteLine(result);}static string Preview(string raw) { string name=raw.Trim(); return name.Length is <1 or >20 ? "Invalid name" : $"Preview: {name}";}Expected result (not executed):
Invalid namePreview: AtlasInvalid namePure functions test the boundary without a Windows dependency. The character limit here counts UTF-16 units, not grapheme clusters.
Apply the concept
Design a WinForms receive-stock form that delegates quantity validation to a presenter. Specify the click flow and behavior after closing.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
WinForms event model — knowledge check
Apply the lesson concepts to the following scenarios.
What typically starts a WinForms button action?
What happens if TextChanged is used?
Why revalidate in Click?
Where should a pure quantity rule live?
What needs cleanup when subscribing to a long-lived publisher?