TechMende.com
Easy Technology Tips, Tricks & Guides

How Events Work in a Windows Form Application

Windows Forms allows you to create desktop applications visually, by dragging UI elements onto a canvas. These UI elements include widgets such as buttons, panels, or checkboxes.

Each UI element receives certain events. For example, you can have a click event for buttons, a changed event for checkboxes, or a drag and drop event for panels.

Events use event handlers or functions, which only execute when that particular event occurs.


Types of Events Used for Different UI Elements

Each UI element has a list of events. There are many courses where you can learn about important UX or UI theories and practices to help you decide what UI elements to use. Here are a few examples of events used by UI elements.

Key Down, Key Up, or Key Press Events

UI elements that allow the user to enter text, such as a text box, can use these events. These events get triggered every time the user presses a key on their keyboard.

These can be useful in scenarios where you have search functionality, and you may need to constantly check what the value of the text box is.


private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
TextBox textbox = (TextBox)sender;
string currentTextBoxValue = textbox.Text;
}

Load Event

The load event occurs when the form or a UI element is rendered on the screen. You can use this event when you want specific functionality to occur at the form or control’s initialization stage.

One scenario where this may be useful is if you want to programmatically add controls to the form while it is still loading.

private void Form1_Load(object sender, EventArgs e)
{
ToolTip toolTip1 = new ToolTip();
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
toolTip1.ShowAlways = true;
toolTip1.SetToolTip(this.button1, "My button1");
toolTip1.Popup += this.ToolTip1_Popup;
}

The tooltip popup event happens when you hover over a UI element on the application, and a tooltip appears. The arguments passed into the event handler allow you to access data about the tooltip, such as its text or size.

private void ToolTip1_Popup(object sender, PopupEventArgs e)
{
ToolTip tooltip = (ToolTip)sender;
string tooltipText = tooltip.GetToolTip(button1);
var tooltipSize = e.ToolTipSize;
}

Drag and Drop Event

Many UI elements can use the drag and drop event, including the panel, button, picture box, group box, and more. This event gets triggered when the user drags a file into the UI element.

private void panel1_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
}

Mouse Over and Mouse Leave Events

The mouse over event fires when the mouse hovers over a UI element. Once the mouse leaves and stops hovering over the element, the mouse leave event gets triggered.

private void button1_MouseLeave(object sender, EventArgs e)
{
Button button = (Button)sender;
var buttonText = button.Text;
}

Checked Changed Event

UI elements that allow the user to select an option can use the checked changed event. This includes radio buttons and checkboxes. The function gets triggered when you check or uncheck the checkbox.

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
CheckState state = checkbox.CheckState;
bool isChecked = checkbox.Checked;
}

Value Changed, Selected Value Changed, or Date Changed Events

The value changed event is available on UI elements that allow you to select an option to change a value. This includes combo boxes, date and time pickers, or the calendar. The function gets triggered when the user selects a new value.

private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
MonthCalendar calendar = (MonthCalendar)sender;
var today = calendar.TodayDate;
var selectedDatesStart = e.Start;
var selectedDatesEnd = e.End;
}

Click Button Event

The click event handler function gets triggered when you click a button.

private void button1_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
string textValue = button.Text;
}

The Structure of an Event Handler

Event handlers have two primary parameters: the sender and an event object.

The sender is a reference to the UI element or object that has triggered the event, such as a button, checkbox, or panel. For example, in a checkbox changed event, the sender would be the checkbox that the user clicked on.


​​The event parameter contains an object that stores data about the event that occurred. This could include the X and Y coordinates of a button click, or the location of the mouse at the moment the event triggers.

private void panel1_DragDrop(object sender, DragEventArgs e)
{
Panel panel = (Panel)sender;
panel.Enabled = false;
var eventData = e.Data;
}

How to Create and Use Event Handlers

First, create a new Winforms Forms application in Visual Studio. If you are new to Windows Forms, there are many clone apps you can make while learning Windows Forms.

Event Handlers on the Canvas

You can generate event handlers from the properties window on the right-hand side of the canvas. Once you have created a new Windows Forms application, create an event handler for the checkbox UI element. This will trigger when the user checks or un-checks the checkbox.

  1. Open the toolbox menu on the left of Visual Studio. Drag and drop a checkbox UI element onto the canvas.
  2. Highlight the checkbox on the canvas.
  3. In the properties window on the right-hand panel, click on the yellow lightning icon to view the list of events. Scroll down to the CheckedChanged event.
  4. Click on the empty space next to the CheckedChanged event. This will automatically generate a new function to handle the event. The function will get created in the code-behind part of the application, in your <ApplicationName>.cs file.
    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
    }

Event Handlers Using the Code Behind

Create a new function in the code behind and link it to the UI element on the canvas.

  1. On the canvas, click and drag a button UI element. By default, the name of the new button will be “button1”.
  2. Open <ApplicationName>.cs. If you have left the default Windows Form application name of “Form1”, this would be Form1.cs.
  3. Inside the Form1 class, create a new function. Make sure that it follows the structure of an event handler, and has two parameters for the sender and the event object.
    private void button1_MouseHoverEvent(object sender, EventArgs e)
    {
    }
  4. Link the event handler to the mouse hover event of button1. You can do this in the constructor.
    public Form1()
    {
    InitializeComponent();
    this.button1.MouseHover += button1_MouseHoverEvent;
    }
  5. Alternatively, you can also link the function to the event using the properties window on the canvas. Open the properties window, and enter the name of your event handler into the MouseHover field. This would be button1_MouseHoverEvent.


How to Use the Same Event Handler Across Multiple Events

You can link the same function to multiple events. In this case, if there was a single function called MouseEvent, you could add that event handler to both the mouse hover and mouse click event. This will then handle both events using the same function.

this.button1.MouseHover += button1_MouseEvent;
this.button1.MouseClick += button1_MouseEvent;

Using Events in a Windows Form Application

A Windows Forms application allows you to drag and drop various UI elements such as buttons, panels, or text boxes onto a canvas. You can add event handlers to these UI elements, based on the different events that can occur within the application.

If you are building a Windows Application, you may also want to add images or graphics as part of your user interface. You can use various C# classes such as the Graphic, Pen, or Color class, which will allow you to draw different types of shapes onto the canvas.

Programming

>>Here is the Original Post!

Leave A Reply

Your email address will not be published.