Chapter III
Chapter III
Note: This lesson has been enhanced in grammar, style, and structure using an AI tool to improve clarity and
readability.
64 BAKHTI RACHID
Chapter III: Graphical user interface development
Modern civil-engineering tools—such as COVADIS, PISTE, ROBBAT, CiviLab, and SAP—are built
around well-designed interfaces that guide the user through each task. Behind these interfaces is
source code, wri en in programming languages like Visual Basic, Delphi, C/C++, or [Link], which
defines the structure and behavior of every window, control, and interac on.
GUI development typically begins by defining what the user needs to see and how they will
interact with the program. Frameworks such as WinForms (for C#/.NET) and Tkinter (for Python)
provide pre-built components—windows, labels, text boxes, bu ons, menus—that can be
arranged to create applica ons tailored to engineering workflows.
A central concept in GUI programming is event handling. GUIs operate based on events: when a
user clicks a bu on, moves the mouse, selects an item, or enters data, an event is generated. The
program must detect these events and execute the appropriate instruc ons. The quality of a GUI
depends heavily on how clearly and efficiently these events are managed.
Tes ng and refinement are essen al steps—developers must ensure that each interac on works
as expected, responds correctly to user input, and produces accurate results.
Building GUI-based applica ons for civil engineering requires understanding not only
programming fundamentals but also the principles of interface design and event-driven logic.
Mastering tools like WinForms and Tkinter enables engineers to create powerful, prac cal
so ware that improves produc vity and enhances the user experience.
65 BAKHTI RACHID
Chapter III: Graphical user interface development
The first version, Visual Studio 97, was released in 1997 and included tools for Visual Basic, Visual
C++, and other languages. Over the following years, Visual Studio grew into a unified environment
capable of suppor ng a large variety of programming languages and technologies.
A major milestone came with Visual Studio .NET (2002), which introduced the .NET Framework,
fundamentally changing how Windows applica ons were designed, compiled, and executed. From
that point onward, Visual Studio became the primary development environment for .NET
applica ons.
Subsequent releases—Visual Studio 2005, 2008, 2010, 2012, 2015, 2017, 2019, 2022—con nued
to expand support for web, cloud, mobile, and cross-pla orm development, while greatly
improving produc vity tools such as IntelliSense, refactoring, and debugging capabili es. Today,
Visual Studio remains a reference IDE in the industry, known for its powerful features and rich
ecosystem. The most recent release is Visual Studio 2026.
An Integrated Development Environment (IDE) is a so ware applica on that brings together all
the tools needed to design, write, test, and maintain programs. Its purpose is to simplify and
streamline the development workflow by combining mul ple tools into a single interface. Key
components of a modern IDE include:
66 BAKHTI RACHID
Chapter III: Graphical user interface development
Debugger: Allows developers to run code step by step, inspect variables, set
breakpoints, and diagnose errors.
Build Tools: Automate compilation, linking, packaging, and generation of executable
files.
Project & Solution Management: Organizes files, dependencies, and settings in a
structured way.
Version Control Integration: Enables direct interaction with Git or other version control
systems.
GUI Designers & Specialized Tools: Visual tools for creating graphical interfaces,
managing databases, designing classes, etc.
Error Checking & Code Analysis: Real-time detection of syntax errors, code suggestions,
and best-practice guidance.
Documentation Tools: Automated generation of comments, XML documentation, and
API references.
Extensions & Plugins: Additional components that can enhance productivity, add
languages, or integrate external tools.
An IDE’s main goal is to help developers write better software, faster, and with fewer errors.
Visual Studio provides a wide range of project templates to help developers start applications
quickly. For GUI development and .NET-based applications, the most relevant project types
include:
67 BAKHTI RACHID
Chapter III: Graphical user interface development
These templates cover different levels of project complexity and allow developers to choose the
structure that best fits their needs—whether they are building desktop applications, component
libraries, or reusable UI controls.
68 BAKHTI RACHID
Chapter III: Graphical user interface development
Mul ple programming languages are available in VS2022 such as Visual basic, C#, C++, F#, JavaScript, and
Python
Addi onally, users have the flexibility to choose the target opera ng system for their developed project.
This selec on can encompass a range of op ons, including Mul pla orm, Windows, Linux, Android, iOS,
macOS, and more.
69 BAKHTI RACHID
Chapter III: Graphical user interface development
One of WinForms' strengths is its rapid applica on development capabili es. Developers can
leverage Visual Studio, Microso 's integrated development environment (IDE), to quickly design,
code, and debug applica ons. This results in shorter development cycles and faster me-to-
market.
In summary, Windows Forms remains a robust choice for crea ng na ve Windows applica ons,
whether it's for business so ware, u li es, games, or any other type of desktop applica on. Its
combina on of a rich control library, rapid development capabili es, and deep integra on with
the .NET ecosystem makes it a go-to solu on for developers aiming to deliver user-friendly and
feature-rich Windows applica ons.
Begin by choosing "Windows Forms App" and proceed by clicking the "Next" bu on.
70 BAKHTI RACHID
Chapter III: Graphical user interface development
Input essen al project details, including the project name, project path, and solu on name.
A erward, click the "Next" bu on.
Now, you have the op on to select the preferred framework. Once you've made your choice,
click the "Create" bu on to ini ate the project setup.
These steps provide a seamless way to ini ate a new WinForms App project in a few simple clicks,
ensuring a smooth and efficient start to your development process.
71 BAKHTI RACHID
Chapter III: Graphical user interface development
72 BAKHTI RACHID
Chapter III: Graphical user interface development
The graphical user interface (GUI) builder for Windows Forms App projects in Visual Studio is a
powerful tool that streamlines the applica on development process. It comprises four essen al
mini-windows, each serving a dis nct purpose:
Toolbox Window: This window is a treasure trove of various tools and controls that
developers can easily access. It simplifies the process of adding bu ons, textboxes, grids,
and other UI elements to the form.
Forms Window: In this window, developers can flex their crea ve muscles and design the
visual layout of the Windows App. It provides an intui ve drag-and-drop interface for
placing controls and arranging them as desired.
Solu on Explorer Window: Naviga ng through the components of your project is a
breeze with this window. It offers a structured view of the project's files, making it easy
to find and manage resources.
Property Window: Tailoring the appearance and behavior of UI elements is made
effortless with the Property window. Developers can select a tool or control and view
and edit its proper es, such as size, color, text, and more.
Together, these four mini-windows empower developers to efficiently create and fine-tune the
user interface of their Windows Forms App projects, promo ng a seamless and produc ve
development experience.
Forms: Forms are the main windows or screens in your applica on. They serve as
containers for other controls and provide the user interface. Forms can be designed
visually using the Windows Forms Designer in Visual Studio or created programma cally.
Controls: Controls are UI (User Interface) elements placed on forms to enable user
interac on. Examples include bu ons, textboxes, labels, checkboxes, radio bu ons, and
more. These controls are added to forms to create the desired user interface.
73 BAKHTI RACHID
Chapter III: Graphical user interface development
Classes: Classes in [Link] are used to define custom data types and contain methods
and proper es that define the behavior of objects. In a Windows Forms applica on, you
can create custom classes to encapsulate specific func onality, such as data handling or
business logic.
Modules: Modules are a way to organize code in [Link]. They are similar to classes but
don't require an instance to be created. Modules o en contain shared procedures and
func ons that can be accessed globally across the applica on.
Event Handlers: Event handlers are methods or func ons that respond to specific events
raised by controls. For example, you can write code in an event handler to handle bu on
clicks or text changes. Event handlers are essen al for crea ng interac ve applica ons.
Resources: Resources are used to store applica on assets such as images, icons, and
strings. They can be embedded in your applica on or stored externally as files. Resources
are typically managed using resource files (.resx) in Visual Studio.
Se ngs: Se ngs allow you to persist user-specific configura on data such as user
preferences or applica on se ngs. These se ngs can be accessed and modified during
run me.
Data Access: In many Windows Forms applica ons, you'll work with databases or other
data sources. You may use classes or libraries to connect to and manipulate data, such as
[Link] for database access.
References: References are links to external libraries or assemblies that your applica on
depends on. These references can include .NET Framework libraries, third-party libraries,
or custom libraries you've created.
Deployment Configura on: Deployment configura on refers to the process of se ng up
and configuring your so ware applica on for distribu on and installa on on end-users'
systems. It involves making decisions and adjustments to ensure that your applica on
can be deployed and run smoothly on various target environments
74 BAKHTI RACHID
Chapter III: Graphical user interface development
These components work together to create a fully func onal Windows Forms applica on in
[Link], allowing you to design a rich user interface and implement the necessary func onality
to meet your applica on's requirements.
75 BAKHTI RACHID
Chapter III: Graphical user interface development
76 BAKHTI RACHID
Chapter III: Graphical user interface development
77 BAKHTI RACHID
Chapter III: Graphical user interface development
Remember, a well-designed menu system enhances user produc vity and sa sfac on, making it
a fundamental aspect of any WinForms applica on.
Applica on 01:
Create a basic menu using a `MenuStrip` control in a WinForms applica on. In this example, we'll
create a File menu with "New File", “Open”, and “Save" op ons and a separator line
1. Drag and drop a `MenuStrip` control from the Toolbox onto your form. It will be placed at the
top of your form by default.
2. Click on the `MenuStrip` control to select it.
3. In the Proper es window, find the `Items` property and click the ellipsis bu on (…) to open the
Menu Designer.
4. In the Menu Designer, add a new menu item under the `MenuStrip` by right-clicking the
`MenuStrip` and choosing "Add" Set the text property to "File."
5. Click the "File" menu to select it, find the `DropDownItems` property and click the ellipsis bu on
(…) to open the Menu Designer. In the Menu Designer, add two submenu items: "New", "Open."
And “Save”. Also add a separator
6. Set the text proper es for "New", "Open." And Save as follows:
"New" for the first submenu item.
"Open" for the second submenu item.
"Save" for the third submenu item.
7. In the Menu Designer, click "OK" to close the Menu Designer.
That's a basic example of crea ng a menu in WinForms. You can expand and customize your menu
with addi onal menu items and func onality as needed for your applica on.
78 BAKHTI RACHID
Chapter III: Graphical user interface development
79 BAKHTI RACHID
Chapter III: Graphical user interface development
1. In the toolbox, find the "ContextMenuStrip" control. It's usually located under the "Menus &
Toolbars" sec on.
2. Drag and drop the `ContextMenuStrip` control onto your form. It won't be visible at run me
but will appear in the component tray at the bo om of the designer.
4. In the Proper es window, click the ellipsis (...) bu on next to the "Items" property to open the
Menu Designer.
5. In the Menu Designer, you can add menu items by right-clicking the `MenuItems` and
choosing "Add"
6. Customize the proper es of the menu items, such as se ng their text, shortcuts, icons, and
event handlers.
7. To make the `ContextMenuStrip` appear when a user right-clicks on a control, select the
control. In the Proper es window, find the "ContextMenuStrip" property and set it to the
`ContextMenuStrip` you've created. This associates the menu with the control.
III.3.6. TextBox
The `TextBox` control is a fundamental component in Windows Forms (WinForms) applica ons,
enabling users to input and edit textual informa on. This control is widely used for various data
entry and text display purposes. In this sec on, we'll explore the `TextBox` control and how to add
it to a WinForms form.
The `TextBox` control offers the following key features:
1. Text Input: Users can type or paste text into the `TextBox`, making it suitable for various data
input tasks, such as user registra on forms, search boxes, and text edi ng.
2. Mul line Text: The `TextBox` can be configured as a single-line input or a mul line text area,
allowing users to enter and edit longer text content.
80 BAKHTI RACHID
Chapter III: Graphical user interface development
3. Read-Only and Disabled: The `TextBox` control can be set to read-only mode or disabled to
prevent user input while s ll displaying informa on.
Adding a TextBox to a WinForms Form:
81 BAKHTI RACHID
Chapter III: Graphical user interface development
82 BAKHTI RACHID
Chapter III: Graphical user interface development
The `Label` control is a fundamental tool for enhancing the clarity and usability of WinForms
applica ons. By adding and customizing labels strategically, you can create intui ve and
informa ve user interfaces that guide users through your applica on's features and func ons.
' Change the text of the label
[Link] = "Hello, this is a Label control!"
' Update the label based on user input (for example, a TextBox)
[Link] = "You entered: " & [Link]
' Change font and color programma cally
[Link] = New Font("Arial", 12, [Link])
[Link] = [Link]
' Display mul line text
[Link] = False
[Link] = New Size(200, 60)
[Link] = "Line 1" & vbCrLf & "Line 2" & vbCrLf & "Line 3"
III.3.8. DataGridView
A DataGridView is a fundamental component in Windows Forms (WinForms) applica ons,
designed to efficiently display and manipulate tabular data. It provides a user-friendly interface
for presen ng data in a grid format, making it a vital tool for crea ng database-driven applica ons,
reports, and data management tools.
83 BAKHTI RACHID
Chapter III: Graphical user interface development
5. Expor ng: Implement export func onality to enable users to save data from the DataGridView
to various file formats like CSV or Excel (the implementa on can be done programma cally in
code).
' Create a DataTable to store data
Dim dt As New DataTable()
' Add columns
[Link]("ID", GetType(Integer))
[Link]("Name", GetType(String))
[Link]("Value", GetType(Double))
' Add sample rows
[Link](1, "Item A", 12.5)
[Link](2, "Item B", 18.9)
[Link](3, "Item C", 7.3)
' Bind the DataTable to the DataGridView
[Link] = dt
' ----------------------------------------
' Read a cell value
' Example: read the "Value" of the first row
Dim firstValue As Double
firstValue = [Link]([Link](0).Cells(2).Value)
[Link]("The value of the first row is: " & firstValue)
' ----------------------------------------
' Set or modify a cell value
' Example: change the "Name" of the second row
[Link](1).Cells(1).Value = "Updated Item B"
III.3.9. Chart
A Chart is an essential component in Windows Forms (WinForms) applications used to visually
represent numerical data in graphical form. It provides a clear and interactive way to display
trends, comparisons, and relationships through various chart types such as line, bar, pie, area, or
scatter plots. This makes the Chart control particularly valuable in applications that involve
scientific data, engineering results, statistics, or any scenario where visual analysis is required.
84 BAKHTI RACHID
Chapter III: Graphical user interface development
1. Drag and Drop: From the Toolbox, drag and drop a Chart control onto your form. It is
located under the "Data" section. Visual Studio will automatically add a default ChartArea
and a default Series.
2. Series Configuration: A Chart is composed of one or more series, each representing a set
of data points. Configure the chart type (e.g., Line, Bar, Pie) and add or remove series in
the designer or in code.
3. Data Binding: Populate the Chart by adding data points or binding it to a data source such
as an array, list, or DataTable. Data can be added manually or dynamically at runtime.
4. Customization: Customize the chart’s appearance by modifying colors, titles, legends,
axes, or gridlines. You can also style markers, labels, and backgrounds to fit your
application’s design.
5. Interactivity: The Chart control supports events such as clicking, hovering, or zooming,
allowing users to interact with the displayed data.
This simple [Link] example adds a line chart with five data points. More complex examples
such as mul ple series, axis tles, legends, or data binding can be added as needed.
Homework:
Create a graphical user interface (GUI) for a WinForms applica on to input data of the grain
size distribu on test.
85 BAKHTI RACHID
Chapter III: Graphical user interface development
Widgets: UI elements like buttons, labels, text entries, checkboxes, and menus.
Windows: The main application window (Tk) or additional windows (Toplevel).
Geometry Managers: Tools like pack(), grid(), and place() to arrange widgets inside a
window.
Event Handling: Binding functions to user actions such as clicks, keypresses, or mouse
movements.
Variables: Tkinter supports StringVar, IntVar, DoubleVar, and BooleanVar for dynamic
widget content.
86 BAKHTI RACHID
Chapter III: Graphical user interface development
87 BAKHTI RACHID
Chapter III: Graphical user interface development
import tkinter as tk
from tkinter import messagebox
root = [Link]()
[Link]("Menu Example")
# Top-level menu
menubar = [Link](root)
file_menu = [Link](menubar, tearoff=0)
file_menu.add_command(label="New", command=lambda: [Link]("Menu",
"New File"))
file_menu.add_command(label="Open", command=lambda: [Link]("Menu",
"Open File"))
file_menu.add_separator()
file_menu.add_command(label="Save", command=lambda: [Link]("Menu",
"Save File"))
menubar.add_cascade(label="File", menu=file_menu)
[Link](menu=menubar)
# Context menu
context_menu = [Link](root, tearoff=0)
context_menu.add_command(label="Option 1")
context_menu.add_command(label="Option 2")
def show_context(event):
context_menu.post(event.x_root, event.y_root)
[Link]("<Button-3>", show_context) # Right-click
[Link]()
Key Features:
88 BAKHTI RACHID
Chapter III: Graphical user interface development
import tkinter as tk
root = [Link]()
[Link]("Entry Example")
label = [Link](root, text="Enter your name:")
[Link]()
entry = [Link](root)
[Link]()
def show_input():
[Link](text="You entered: " + [Link]())
III.4.5. Label
The Label widget displays text, images, or both. Labels are read-only and often used to describe
other widgets or show output dynamically.
Key Features:
import tkinter as tk
root = [Link]()
[Link]("Label Example")
label = [Link](root, text="Hello, this is a Label!", font=("Arial", 12, "bold"), fg="blue")
[Link]()
def update_label():
89 BAKHTI RACHID
Chapter III: Graphical user interface development
Key Features:
import tkinter as tk
from tkinter import ttk
root = [Link]()
[Link]("Treeview Example")
# Treeview with columns
tree = [Link](root, columns=("ID", "Name", "Value"), show='headings')
[Link]("ID", text="ID")
[Link]("Name", text="Name")
[Link]("Value", text="Value")
[Link]()
# Insert rows
[Link]("", [Link], values=(1, "Item A", 12.5))
[Link]("", [Link], values=(2, "Item B", 18.9))
[Link]("", [Link], values=(3, "Item C", 7.3))
[Link]()
90 BAKHTI RACHID
Chapter III: Graphical user interface development
Key Features:
import tkinter as tk
from [Link].backend_tkagg import FigureCanvasTkAgg
from [Link] import Figure
root = [Link]()
[Link]("Chart Example")
# Matplotlib Figure
fig = Figure(figsize=(5, 4))
ax = fig.add_subplot(111)
# Sample Data
x = [0, 1, 2, 3, 4]
y = [5, 8, 3, 10, 7]
[Link](x, y, marker='o', linestyle='-', color='blue')
ax.set_title("Line Chart Example")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
# Embed Figure in Tkinter
canvas = FigureCanvasTkAgg(fig, master=root)
[Link]()
canvas.get_tk_widget().pack()
[Link]()
Homework
91 BAKHTI RACHID
Chapter III: Graphical user interface development
In a GUI environment, almost everything is event-driven. The application remains idle until the
user interacts with a control (button, textbox, chart, etc.) or sends input through the keyboard or
mouse. Each control exposes a set of events, allowing developers to customize how the
application behaves. For example, a button may trigger a Click event, a TextBox may trigger a
TextChanged event whenever its content is modified, and a DataGridView may react to CellClick
or SelectionChanged events. Mastering event handling enables developers to create responsive,
dynamic, and user-friendly applications.
Both WinForms ([Link]) and Tkinter (Python) implement event handling, but they do so using
different syntaxes and mechanisms. In WinForms, events are typically handled using the Handles
keyword or the AddHandler statement. Each event is tied to a method—called an event handler—
that contains the actions to be executed when that event occurs. For example, writing Handles
[Link] automatically connects the method to the Click event of a specific button.
WinForms also supports a wide variety of advanced events such as mouse position tracking,
92 BAKHTI RACHID
Chapter III: Graphical user interface development
keyboard shortcuts, form lifecycle events (load, closing), and data-related events (grid selection,
value changes).
Tkinter, on the other hand, uses a different style of event handling. Basic controls like Buttons use
the command= parameter to link a function directly to a click action. For more complex events,
such as keyboard input or mouse interactions, Tkinter uses the bind() method, which attaches
events to functions using event codes like <Button-1>, <KeyRelease>, or <Motion>. Tkinter also
relies heavily on "callbacks": functions that the framework calls automatically when an event
occurs. This model gives developers fine-grained control over user interactions and custom
behavior.
Understanding event handling is crucial because it forms the backbone of how GUI software
operates. Without events, programs cannot react to user input, making interaction impossible.
Whether the goal is to create a simple form that updates labels based on user input, build data-
entry applications, or design advanced engineering software with dynamic charts and
visualization tools, event-driven logic is always at the core.
Although WinForms and Tkinter handle events differently, the underlying principles remain the
same. A user action triggers an event, the event is captured by the application, and the
corresponding handler executes the appropriate response. Mastering these concepts is essential
for developing robust and intuitive GUI applications in both [Link] and Python.
93 BAKHTI RACHID
Chapter III: Graphical user interface development
Click
TextChanged
SelectedIndexChanged
CellClick
FormClosing
MouseMove
etc.
94 BAKHTI RACHID
Chapter III: Graphical user interface development
import tkinter as tk
root = [Link]()
def on_click():
print("Button clicked!")
button = [Link](root, text="Click Me", command=on_click)
[Link]()
[Link]()
Example 1 — Button Click Event
Tkinter does not have a na ve TextChanged event,
but we can use a StringVar with trace():
import tkinter as tk
root = [Link]()
def text_changed(*args):
print("You typed:", text_var.get())
text_var = [Link]()
text_var.trace("w", text_changed)
[Link]()
Example 2 — Detec ng Text Change in Entry
95 BAKHTI RACHID
Chapter III: Graphical user interface development
import tkinter as tk
from tkinter import k
root = [Link]()
def on_row_selected(event):
selected = [Link] on()
value = [Link](selected)['values']
print("Selected row:", value)
[Link]("<<TreeviewSelect>>", on_row_selected)
[Link]()
Example 3 — Treeview Row Selec on Event
96 BAKHTI RACHID