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
Event | Description | Typical Use |
---|---|---|
Click | Occurs when the control is clicked. | Submit a form or trigger an action. |
Load | Raised when the control is loaded. | Initialize data or UI elements. |
Paint | Occurs when the control is redrawn. | Custom drawing. |
KeyDown | Fires when a key is pressed while the control has focus. | Keyboard shortcuts. |
TextChanged | Raised when the text property changes. | Validate input. |
MouseEnter | Occurs 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.