Lecture Notes: Introduction to Events, Fundamentals of Event-Driven Programming, Message Handling, User Interface (Using C#)
1. Introduction to Events
Events are one of the core concepts in event-driven programming, allowing an application to respond to various user actions or system triggers.
What is an Event?
An event is a notification or signal that something has happened in the system. Common examples include:
Mouse clicks
Key presses
Window resizing
File I/O completion
Event-Driven Programming in C#
C# supports event-driven programming through the use of:
Delegates: A type-safe function pointer used to hold references to methods.
Events: Based on delegates, these are triggered when something happens. They allow subscribers (methods) to respond to that event.
Event Syntax in C#
To declare and trigger events, C# uses the following syntax:
// Step 1: Declare a delegate
public delegate void EventHandler();
// Step 2: Declare an event based on the delegate
public event EventHandler OnClick;
// Step 3: Define a method to trigger the event
protected virtual void TriggerClick()
{
if (OnClick != null)
OnClick();
}
Built-in Events
C# provides built-in event handlers in the System and System.Windows.Forms namespaces. Some common events:
Click: Occurs when a control, such as a button, is clicked.
MouseMove: Triggered when the mouse is moved over a control.
KeyDown: Triggered when a key is pressed.
2. Fundamentals of Event-Driven Programming
What is Event-Driven Programming?
Event-driven programming is a programming paradigm in which the flow of the program is determined by events, such as user actions, sensor outputs, or messages
from other programs.
Key Features:
1. Event Loop: The program waits for an event (such as a button click or a file being loaded) and responds to it.
2. Event Handlers: Functions or methods that contain the logic executed when an event occurs.
3. Subscribers and Publishers: The publisher raises the event, and the subscriber listens and reacts to it.
Event Handling Mechanism in C#:
Delegate: Acts as a pointer to a method.
Event: A special delegate type that is used to signal the occurrence of something.
Handlers: Methods assigned to an event delegate that execute when the event is raised.
Event Handling in Practice
First, declare a delegate for the event.
Then, define an event using that delegate.
Attach methods (event handlers) to this event to handle it.
public class Button
{
// Declare the event using EventHandler delegate
public event EventHandler Click;
public void SimulateClick()
{
// Raise the event
if (Click != null)
Click(this, EventArgs.Empty);
}
}
// Usage
Button btn = new Button();
btn.Click += (sender, e) => Console.WriteLine("Button Clicked!");
btn.SimulateClick();
3. Message Handling
What is Message Handling?
In a graphical user interface (GUI), each action (like clicking a button or moving the mouse) generates a message. This message is handled by the application to
determine the appropriate response.
Windows Message Loop
In Windows-based applications (like WinForms or WPF), the message loop listens for system-generated messages.
The system sends messages for user actions like mouse movement, key presses, etc.
Message Flow in C#:
1. Capture: The system captures user input (e.g., mouse click).
2. Queue: The input is translated into a message and placed in a message queue.
3. Dispatch: The message is dispatched to the appropriate window procedure (method) for handling.
C# Message Handling Example:
In C# WinForms, the WndProc method is used to handle low-level window messages:
protected override void WndProc(ref Message m)
{
const int WM_PAINT = 0x000F;
if (m.Msg == WM_PAINT)
{
// Handle paint event
Console.WriteLine("Window needs repainting.");
}
base.WndProc(ref m); // Call base method to process other messages
}
This low-level message handling is typically abstracted away in modern frameworks like WinForms and WPF.
4. User Interface (UI) in C#
Understanding User Interfaces (UI)
A User Interface (UI) is the space where interactions between humans and machines occur. In Windows Forms and WPF, UIs are composed of various controls
like buttons, textboxes, and labels.
Components of UI in C#
Forms: Containers for UI elements like buttons, labels, and textboxes.
Controls: Individual components that enable user interaction (e.g., Button, TextBox, Label).
Creating a Simple User Interface in C#
Below is a basic example of creating a UI using Windows Forms in C#:
using System;
using System.Windows.Forms;
public class MainForm : Form
{
private Button button;
public MainForm()
{
// Initialize components
button = new Button();
button.Text = "Click Me!";
button.Location = new System.Drawing.Point(50, 50);
button.Click += Button_Click; // Assign event handler to the button click event
// Add controls to the form
this.Controls.Add(button);
}
private void Button_Click(object sender, EventArgs e)
{
MessageBox.Show("Button clicked!");
}
[STAThread]
static void Main()
{
// Start the application
Application.EnableVisualStyles();
Application.Run(new MainForm());
}
}
Handling UI Events
Click: Invoked when a button is clicked.
TextChanged: Fires when the text in a TextBox changes.
KeyPress: Responds to a key being pressed within a control.
Designing User Interfaces
Layout Management: Using containers like panels, FlowLayoutPanel, TableLayoutPanel to arrange controls.
Styles and Themes: Modify control properties like BackColor, Font, and ForeColor to style the UI.
Event Binding to Controls
Controls are bound to event handlers using the event's += operator in C#. For example:
button.Click += new EventHandler(Button_Click);
Summary
Events allow the application to respond to user actions or system triggers.
Event-driven programming controls the flow of an application through events, event handlers, and subscribers.
Message handling deals with low-level system messages, abstracted through C# frameworks.
User Interface design in C# includes forms and controls that are connected to event handlers, making interaction possible.