A graphical user interface (GUI) allows a user to interact visually with a program.
GUIs are built from GUI controls.
GUI controls are objects that can display information on the screen or enable users to interact with an app via the mouse, keyboard or some other form of input.
Windows Forms are used to create the GUIs for programs.
A Form
is a graphical element that appears on the desktop; it can be a dialog, a window or an MDI (multiple document interface) window.
A component is an instance of a class that implements the IComponent
interface, which defines the behaviors that components must implement, such as how the component is loaded.
A control is a component that has a graphical representation at runtime.
Some components lack graphical representations (e.g., class Timer
of namespace System.Windows.Forms
). Such components are not visible at runtime.
When there are several windows on the screen, the active window is the frontmost and has a highlighted title bar. A window becomes the active window when the user clicks somewhere inside it.
The active window is said to “have the focus.”
A Form
is a container for controls and components.
Normally, a user interacts with an app’s GUI to indicate the tasks that the app should perform.
GUIs are event driven.
When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform a task. Common events include clicking a Button
, typing in a TextBox
, selecting an item from a menu, closing a window and moving the mouse.
A method that performs a task in response to an event is called an event handler, and the overall process of responding to events is known as event handling.
An event handler executes only when the user performs the specific event.
Each event handler receives two parameters when it’s called. The first—an object
reference typically named sender
—is a reference to the object that generated the event. The second is a reference to an event arguments object of type EventArgs
(or one of its derived classes), which is typically named e
. This object contains additional information about the event that occurred.
EventArgs
is the base class of all classes that represent event information.
Visual Studio generates the code that creates and initializes the GUI that you build in the GUI design window. This auto-generated code is placed in the Designer.cs
file of the Form
.
The auto-generated code that defines the GUI is part of the Form
’s class. The use of the partial
modifier in the class declaration allows the class to be split among multiple files.
The Designer.cs
file declares the controls you create in Design mode.
The Designer.cs
file includes the Dispose
method for releasing resources and method Initial-izeComponent
, which sets the properties of the Form
and its controls.
Visual Studio uses the code in InitializeComponent
to create the GUI you see in design view. Changing the code in this method may prevent Visual Studio from displaying the GUI properly.
The control that generates an event is known as the event sender.
An event-handling method—known as the event handler—responds to a particular event that a control generates.
When an event occurs, the event sender calls its event handler to perform a task.
The .NET event-handling mechanism allows you to choose your own names for event-handling methods. However, each event-handling method must declare the proper parameters to receive information about the event that it handles.
Event handlers are connected to a control’s events via special objects called delegates.
A delegate object holds a reference to a method with a signature specified by the delegate type’s declaration.
GUI controls have predefined delegates that correspond to every event they can generate.
Since each event handler is declared as a delegate, the event sender can simply call the appropriate delegate when an event occurs. The delegate’s job is to invoke the appropriate method.
Event delegates represent a set of delegate objects that all have the same signature.
When an event occurs, its sender calls every method referenced by a multicast delegate. Multicast delegates enable several methods to be called in response to a single event.
Event delegates derive from class MulticastDelegate
, which derives from class Delegate
(both from namespace System
).
Double-clicking a control in the designer creates an event handler for a control’s default event.
Typically, controls can generate many different events, and each can have its own event handler.
You can create additional event handlers through the Properties window.
If you select a control on the Form
, then click the Events icon (the lightning bolt icon) in the Properties window, all the events for that control are listed in the window. You can double click an event’s name to display the event handler in the editor, if the event handler already exists, or to create the corresponding event handler.
You can select an event, then use the drop-down list to its right to choose an existing method that should handle that event. The methods that appear in this drop-down list are the Form
class’s methods that have the proper signature to be an event handler for the selected event.
A single event handler can handle multiple events from multiple controls.
Read the Visual Studio documentation to learn about the different events raised by each control. To do this, select a control in the IDE and press the F1 key to display that control’s online help. The web page that’s displayed contains basic information about the control’s class. Click the link to the list of events for that control to display the supported events for that control.
Controls derive from class Control
(of namespace System.Windows.Forms
).
The Select
method transfers the focus to a control and makes it the active control.
The Enabled
property indicates whether the user can interact with a control to generate an event.
A programmer can hide a control from the user without disabling the control by setting the Visible
property to false
or by calling method Hide
.
Anchoring causes controls to remain at a fixed distance from the sides of the container even when the control is resized.
Docking attaches a control to a container such that the control stretches across an entire side or fills all the remaining space.
The Padding
property specifies the distance between the docked controls and the Form
edges.
The Anchor
and Dock
properties of a Control
are set with respect to the Control
’s parent container, which could be a Form
or other parent container (such as a Panel
).
The minimum and maximum Form
(or other Control
) sizes can be set via properties MinimumSize
and MaximumSize
, respectively.
When dragging a control across a Form
, blue lines (known as snap lines) appear to help you position the control with respect to other controls and the Form
’s edges.
Visual Studio also provides the Format menu, which contains several options for modifying your GUI’s layout.
Label
s, TextBox
es and Button
sLabels provide text information (as well as optional images) that the user cannot directly modify.
A textbox (class TextBox
) is an area in which text either can be displayed by a program or in which the user can type text via the keyboard.
A password TextBox
is a TextBox
that hides the information entered by the user. As the user types, the password TextBox
masks the user input by displaying a password character (usually *
). If you set the UseSystemPasswordChar
property to true
, the TextBox
becomes a password TextBox
.
A button is a control that the user clicks to trigger an action in a program or to select an option.
All the button classes derive from class ButtonBase
(namespace System.Windows.Forms
), which defines common button features.
GroupBox
es and Panel
sGroupBox
es and Panel
s arrange controls on a GUI.
GroupBox
es and Panel
s are typically used to group several controls of similar functionality or several controls that are related in a GUI.
GroupBox
es can display a caption (i.e., text) and do not include scrollbars, whereas Panel
s can include scrollbars and do not include a caption.
GroupBox
es have thin borders by default; Panel
s can be set so that they also have borders, by changing their BorderStyle
property.
The controls of a GroupBox
or Panel
are added to their Controls
properties.
To enable a Panel
’s scrollbars, set the Panel
’s AutoScroll
property to true
. If the Panel
is resized and cannot display all of its controls, scrollbars appear.
CheckBox
es and RadioButton
sCheckBox
es and RadioButton
s can be in the on/off or true/false states.
Classes CheckBox
and RadioButton
are derived from class ButtonBase
.
A CheckBox
is a small square that either is blank or contains a check mark. When a CheckBox
is selected, a check mark appears in the box. Any number of CheckBox
es can be selected at a time.
A CheckBox
can be configured to have three states—checked, unchecked, and indeterminate—by setting its ThreeState
property to true
.
Font styles can be combined via bitwise operators, such as the logical OR (|
) operator or the logical exclusive OR (^
) operator.
RadioButton
s (defined with class RadioButton
) are similar to CheckBox
es in that they also have two states: selected and not selected (also called deselected).
RadioButton
s normally appear as a group, in which only one RadioButton
can be selected at a time. The selection of one RadioButton
in the group forces all the others to be deselected. Therefore, RadioButton
s are used to represent a set of mutually exclusive options.
All RadioButton
s added to a container become part of the same group.
PictureBox
esA PictureBox
displays an image.
The Image
property specifies the image that’s displayed
The SizeMode
property indicates how the image is displayed (Normal
, StretchImage
, Autosize
, CenterImage
, or Zoom
).
You can embed images into a project as resources.
Embedded image files appear in a folder named Resources in the Solution Explorer.
The Resources
class (of a project’s Properties
namespace) provides access to a project’s resources.
Class ResourceManager
provides methods for programmatically accessing a project’s resources.
To access an image (or any other resource) in the project’s resources, you use the method Get-Object
of class ResourceManager
, which takes as an argument the resource name as it appears in the Resources tab and returns the resource as an Object
.
The Resources
class provides direct access to the resources you define with expressions of the form Resources.
resourceName.
ToolTip
sTool tips help you become familiar with a Form
’s features and serve as useful reminders for each control’s functionality. In the Properties window, you can specify a tool tip for a control by setting the ToolTip on componentName entry, where componentName is the name of the ToolTip
component.
The ToolTip
component can be used to add tool tips to your app.
The ToolTip
component is placed in the component tray—the gray region below the Form
in Design mode.
NumericUpDown
ControlAt times you’ll want to restrict a user’s input choices to a specific range of numeric values. This is the purpose of the NumericUpDown
control.
The NumericUpDown
control appears as a TextBox
, with two small Button
s on the right side, one with an up arrow and one with a down arrow. By default, a user can type numeric values into this control as if it were a TextBox
or click the up and down arrows to increase or decrease the value in the control, respectively.
The largest and smallest values in the range are specified with the Maximum
and Minimum
properties, respectively (both are of type decimal
).
The Increment
property (of type decimal
) specifies by how much the current number in the control changes when the user clicks the control’s up and down arrows.
Setting a NumericUpDown
control’s ReadOnly
property to true
specifies that the user can only use the up and down arrows to modify the value in the NumericUpDown
control.
Mouse events, such as clicks and moves, are generated when the mouse interacts with a control.
Mouse events can be handled for any subclass of System.Windows.Forms.Control
.
Class MouseEventArgs
contains information related to the mouse event, such as the x- and y-coordinates of the mouse pointer, the mouse button pressed (Right
, Left
or Middle
) and the number of times the mouse was clicked.
Whenever the user holds down a mouse button, the system generates a MouseDown
event.
When the user releases the mouse button (to complete a “click” operation), the system generates a single MouseUp
event.
Whenever the mouse moves over a control, the MouseMove
event for that control is raised.
Key
events occur when keys on the keyboard are pressed and released.
There are three key events—KeyPress
, KeyUp
and KeyDown
.
The KeyPress
event occurs when the user presses a character key, or the space or backspace keys. The specific key can be determined with property KeyChar
of the event handler’s KeyPressEventArgs
argument.
The KeyPress
event does not indicate whether modifier keys were pressed when a key event occurred. If this information is important, the KeyUp
or KeyDown
events should be used.