WinForms Events

Understanding Events in WinForms

WinForms uses an event-driven programming model that allows controls to respond to user actions such as clicks, key presses, and mouse movements. Each control exposes a set of events that you can handle in your code.

Commonly Used Events

EventDescriptionTypical Use
ClickOccurs when the control is clicked.Submit a form or trigger an action.
LoadRaised when the control is loaded.Initialize data or UI elements.
PaintOccurs when the control is redrawn.Custom drawing.
KeyDownFires when a key is pressed while the control has focus.Keyboard shortcuts.
TextChangedRaised when the text property changes.Validate input.
MouseEnterOccurs when the mouse pointer enters the control's bounds.Hover effects.

Subscribing to Events

You can subscribe to an event either in the designer or programmatically:

// Programmatic subscription
button1.Click += new EventHandler(Button1_Click);

private void Button1_Click(object sender, EventArgs e)
{
    MessageBox.Show("Button clicked!");
}

Best Practices

  • Keep event handlers short and focused.
  • Avoid long-running operations on the UI thread; use async patterns.
  • Detach event handlers when no longer needed to prevent memory leaks.
  • Use descriptive method names for event handlers.