![]() |
Behaviors and Events of Windows Controls |
|
Fundamentals of Controls Methods |
|
Introduction |
|
A method is a procedure created as a member of a class. Methods are used to access or manipulate the characteristics of an object or a variable. There are mainly two categories of methods you will use in your classes:
|
As you should know already, every class has a fundamental method called a default constructor. Every control of the .NET Framework is based on a class that has a default constructor and most of those classes have only one constructor: the default. The default constructor allows you to instantiate the class without necessarily initializing it. To use it, you must know the name of the control you want to use since each control bears the same name as its class. Here is an example: Imports System
Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Public Class WinControls
Inherits Form
Private btnReset As Button
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
btnReset = New Button()
End Sub
Public Shared Function Main() As Integer
Application.Run(New WinControls())
Return 0
End Function
End Class
End Module
If you are not planning to use a control straight from the .NET Framework, you can also create your own class that is derived from the class of the control, as we have mentioned in previous lessons. As mentioned in the previous lesson, after instantiating a control, it is available but the user cannot see. Each control that acts as a parent of another control has a property called Controls. This property, which is a ControlCollection type, is equipped with an Add() method. If you want to display the new control to the user, you should pass it to the Control.Controls.Add() method. Here is an example: Imports System
Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Public Class WinControls
Inherits Form
Private btnReset As Button
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
btnReset = New Button()
Controls.Add(btnReset)
End Sub
Public Shared Function Main() As Integer
Application.Run(New WinControls())
Return 0
End Function
End Class
End Module
This displays the control to the user. After using a control, it must be destroyed. Another detail of Windows controls is that they use or consume computer resources during their lifetime. When the controls are not used anymore, such as when their application closes, these resources should be freed and given back to the operating system to make them available to other controls. This task can be performed using the Dispose() method to the Control class, which can then be overridden by its child controls. The syntax of the Control.Dispose() method is: Protected Overrides Sub Dispose(disposing As Boolean) This method takes one argument, disposing, that indicates how the resources would be released. If this argument is passed with a False value, only the unmanaged resources would be released. If it is passed as True, then both managed and unmanaged resources would be released.
In the previous lesson, we saw that you could call the Visible property to hide a visible control or to display a hidden control. Besides the Visible property, you can also display a control using the Show() method. Its syntax is: Public Sub Show() When you use this method, if the control is visible, nothing would happen. If it were hidden, then it would be revealed. The Show() method internally sets the Visible property to true. We also saw that, to hide a control, you could set its Visible property to False. In the same way, to hide a control, you call can the Control.Hide() method. Its syntax is: Public Sub Hide() Keep in mind that hiding a control does not destroy it.
Once a control is visible, the user can use it. Some controls allow the user only to read their text or view what they display. Some other controls allow the user to retrieve their value or to change it. To perform such operations, the user must first give focus to the control. The focus is a visual aspect that indicates that a control is ready to receive input from the user. Various controls have different ways of expressing that they have received focus. Button-based controls indicate that they have focus by drawing a dotted rectangle around their caption. In the following picture, the button on the right has focus: ![]() A text-based control indicates that it has focus by displaying a blinking caret. A list-based control indicates that it has focus when one of its items has a surrounding dotted rectangle: ![]() To give focus to a control, the user can press a key such as Tab. To programmatically give focus to a control, call the Focus() method.
In the previous lesson, we saw how you could position controls visually or manually. In some cases, you end up with one control positioned on top of another. Of course the first remedy that comes in mind would consist of moving one of the controls away from the other. This would also imply sometimes that you would have to enlarge and/or heighten the controls' container. There are situations that either you don't want to resize the parent or you can't: your only solution is to have one control on top of another. Fortunately, you can cope with this situation by specifying, when needed, what control at what time should be displayed to the user. When one control is positioned on top of another, they use a third axis whose origin, like that or the other axes, is on the top-left corner of the parent. This third axis, also considered the z-axis, is oriented so that it moves from the monitor towards the user. The operating system is in charge of positioning and drawing the objects on the screen. You as the programmer can direct the operating system as to what object should be on top and what object should be behind. To support these changes the Control class uses two methods that its appropriate children derive also. When a control A is positioned behind a control be, this causes control be either partially or completely hidden. If you want the control A to change its z-order and become on top of control B, you can call its BringToFront() method. The syntax of this method is: Public Sub BringToFront() On the other hand, if a control B is positioned on top of a control A, if you want control B to become positioned behind control A, you can call control B's SendToBack() method. Its syntax is: Public Sub SendToBack() After the controls have been positioned, at any time, when you access a control, if you want to know whether that control is the most top object, you can call its GetTopLevel() method. Its syntax is: Protected Function GetTopLevel As Boolean
The Windows controls available from the .NET Framework and that we will user in our lessons. They are equipped with various methods ready to be used. Of course, no library can surely provide every single type of method that every programmer would use. For this reason, it will not be unusual that you need a method that is not available for a control you are using. In the same way, when you create a Windows Application that is based on a Form class, you will likely need a method that is not defined in the Form class. In this case, you can create your own and new method. A method is created like a normal procedure. If you want to add it to a form, you can open the Code Editor and write your procedure outside of any existing procedure. Here is an example: Imports System
Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Public Class WinControls
Inherits Form
Private btnReset As Button
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
btnReset = New Button()
btnReset.Text = "Reset"
btnReset.Location = New Point(20, 20)
Controls.Add(btnReset)
End Sub
Private Function CalculateRectangleArea(ByVal Recto As Rectangle) As Double
Return Recto.Width * Recto.Height
End Function
Public Shared Function Main() As Integer
Application.Run(New WinControls())
Return 0
End Function
End Class
End Module
In the same way, if you derive a class from one of the existing classes because you want to get a custom control from it, you can declare a new method as you see fit and use it appropriately. Probably the best way is to let the Code Editor insert the new method based on your specifications. To do that, in the Class View, first expand the name of the project. Then, right-click the name of the class where you want to add a new method, position the mouse on Add, and click Add Method. This would open the C# Method Wizard dialog box you can fill out and click Finish. After the method's body has been defined you
Among all the languages of the .NET Framework and Microsoft Visual Studio, Visual Basic has the largest and the most impressive library of functions. There are so many of these functions, we cannot review them here.
The C and C++ concept of function pointer was very useful when programming for the Microsoft Windows operating systems because the Win32 library relies on the concept of callback functions to process messages. For this reason and because of their functionality, callback functions were carried out in the .NET Framework but they were defined with the name of delegate. A delegate is a special type of user-defined variable that is declared globally, like a class. In fact, a delegate is created like an interface but appearing as a method. Based on this, a delegate provides a template for a method, like an interface provides a template for a class. Like an interface, a delegate is not defined. Its role is to show what a useful method would look like. To support this concept, a delegate can provide all the necessary information that would be used on a method. This includes a return type, either no argument or one or more arguments.
To declare a delegate, you use the delegate keyword. The basic formula used to create a delegate is: [modifier] Delegate Name (parameter(s)) As ReturnType The modifier factor can be Public, Private, or Friend. The Delegate keyword is required. The Name must be a valid name for a procedure. Because a delegate is some type of a template for a procedure, you must use parentheses. If this procedure will not take any argument, you can leave the parentheses empty. The ReturnType can be any of the data types we have used so far. Here is an example of creating a delegate: Imports System.Windows.Forms
Module Exercise
Delegate Sub Simple()
Public Class Starter
Inherits Form
Dim components As System.ComponentModel.Container
Public Sub New()
End Sub
Public Sub InitializeComponent()
End Sub
End Class
End Module
After declaring a delegate, remember that it only provides a template for a procedure, not an actual function. Before using it, you must define a procedure that would carry an assignment the procedure is supposed to perform. That procedure must have the same return type and the same (number of) argument(s), if any. Here is an example: Imports System.Windows.Forms
Module Exercise
Delegate Sub Simple()
Public Class Starter
Inherits Form
Dim components As System.ComponentModel.Container
Public Sub New()
End Sub
Public Sub InitializeComponent()
End Sub
End Class
Private Sub Welcome()
End Sub
End Module
After implementing the procedure, you can associate it to the name of the delegate. To do that, where you want to use the procedure, declare a variable of the type of the delegate using the New operator. In the parentheses of the constructor, access the name of the procedure by its address, using the AddressOf operator. Here is an example that uses a delegate: Imports System.Windows.Forms
Module Exercise
Delegate Sub Simple()
Public Class Starter
Inherits Form
Dim components As System.ComponentModel.Container
Public Sub New()
End Sub
Public Sub InitializeComponent()
Dim Announce As Simple = New Simple(AddressOf Welcome)
End Sub
End Class
Private Sub Welcome()
End Sub
Function Main() As Integer
Dim frmStart As Starter
frmStart = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
You can also declare a delegate that returns a value. When defining a function that would be associated with the delegate, remember that that function must return the same type of value. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Private txtOperation As TextBox
Delegate Function Addition() As Double
Public Class Starter
Inherits Form
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
Dim add As Addition = New Addition(AddressOf Plus)
txtOperation = New TextBox
txtOperation.Location = New Point(100, 20)
Controls.Add(txtOperation)
txtOperation.Text = CStr(add())
End Sub
End Class
Private Function Plus() As Double
Dim a As Double = 248.66, b As Double = 50.28
Plus = a + b
End Function
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
This would produce: ![]()
In the above introductions, we associated delegates with general procedures. Because delegates are usually declared globally, that is outside of a class, they can be associated with almost any function of the application, provided the function has the same return type and the same (number of) argument(s), if any, as the delegate. When you create a procedure that would be associated with a delegate, you can also define it as Shared. Different functions can be associated to delegates. Here is an example of two functions associated with a common delegate: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Delegate Function Multiplication() As Double
Public Class Cube
Private _side As Double
Public Property Side() As Double
Get
Return _side
End Get
Set(ByVal value As Double)
_side = value
End Set
End Property
Public Sub New()
_side = 0
End Sub
Public Sub New(ByVal s As Double)
_side = s
End Sub
Public Function Area() As Double
Return 6 * _side * _side
End Function
Public Function Volume() As Double
Return _side * _side * _side
End Function
End Class
Public Class Starter
Inherits Form
Private lblSide As Label
Private txtSide As TextBox
Private lblArea As Label
Private txtArea As TextBox
Private lblVolume As Label
Private txtVolume As TextBox
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
Dim SmallBox As Cube = New Cube(25.58)
Text = "Cube Calculation"
lblSide = New Label
lblSide.Location = New Point(21, 19)
lblSide.Text = "Side:"
lblSide.AutoSize = True
txtSide = New TextBox
txtSide.Location = New Point(87, 16)
lblArea = New Label
lblArea.Location = New Point(21, 47)
lblArea.Text = "Area:"
lblArea.AutoSize = True
txtArea = New TextBox
txtArea.Location = New Point(87, 44)
lblVolume = New Label
lblVolume.Location = New Point(21, 75)
lblVolume.Text = "Volume:"
lblVolume.AutoSize = True
txtVolume = New TextBox
txtVolume.Location = New Point(87, 72)
Controls.Add(lblSide)
Controls.Add(txtSide)
Controls.Add(lblArea)
Controls.Add(txtArea)
Controls.Add(lblVolume)
Controls.Add(txtVolume)
Dim AreaDefinition As Multiplication = _
New Multiplication(AddressOf SmallBox.Area)
Dim VolDefinition As Multiplication = _
New Multiplication(AddressOf SmallBox.Volume)
txtSide.Text = CStr(SmallBox.Side)
txtArea.Text = CStr(SmallBox.Area)
txtVolume.Text = CStr(SmallBox.Volume)
End Sub
End Class
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
This would produce:
If you want to associate a procedure that takes arguments to a delegate, when declaring the delegate, provide the necessary argument(s) in its parentheses. Here is an example of a delegate that takes two arguments (and returns a value): Module Exercise
Delegate Function Multiplication(ByVal value As Double) As Double
End Module
When defining the associated procedure, besides returning the same type of value, make sure that the procedure takes the same number of arguments. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Delegate Function Multiplication(ByVal value As Double) As Double
Public Function Area(ByVal Side As Double) As Double
Return 6 * Side * Side
End Function
End Module
To associate the procedure, declare a variable of the type of delegate and access the name of the procedure using the AddressOf operator. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Delegate Function Multiplication(ByVal value As Double) As Double
Public Function Area(ByVal Side As Double) As Double
Return 6 * Side * Side
End Function
Public Class Starter
Inherits Form
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
Dim AreaDefinition As Multiplication = New Multiplication(AddressOf Area)
End Sub
End Class
End Module
When accessing the delegate, call the Invoke() method that the delegates inherit from their parent the Delegate class. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Delegate Function Multiplication(ByVal value As Double) As Double
Public Function Area(ByVal Side As Double) As Double
Return 6 * Side * Side
End Function
Public Function Volume(ByVal Side As Double) As Double
Return Side * Side * Side
End Function
Public Class Starter
Inherits Form
Private lblSide As Label
Private txtSide As TextBox
Private lblArea As Label
Private txtArea As TextBox
Private lblVolume As Label
Private txtVolume As TextBox
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
Dim _side As Double = 46.95
Text = "Cube Calculation"
lblSide = New Label
lblSide.Location = New Point(21, 19)
lblSide.Text = "Side:"
lblSide.AutoSize = True
txtSide = New TextBox
txtSide.Location = New Point(87, 16)
lblArea = New Label
lblArea.Location = New Point(21, 47)
lblArea.Text = "Area:"
lblArea.AutoSize = True
txtArea = New TextBox
txtArea.Location = New Point(87, 44)
lblVolume = New Label
lblVolume.Location = New Point(21, 75)
lblVolume.Text = "Volume:"
lblVolume.AutoSize = True
txtVolume = New TextBox
txtVolume.Location = New Point(87, 72)
Controls.Add(lblSide)
Controls.Add(txtSide)
Controls.Add(lblArea)
Controls.Add(txtArea)
Controls.Add(lblVolume)
Controls.Add(txtVolume)
Dim AreaDefinition As Multiplication = _
New Multiplication(AddressOf Area)
Dim VolDefinition As Multiplication = _
New Multiplication(AddressOf Volume)
txtSide.Text = CStr(_side)
txtArea.Text = CStr(AreaDefinition.Invoke(_side))
txtVolume.Text = CStr(VolDefinition.Invoke(_side))
End Sub
End Class
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
Notice that only the name of the method is passed to the delegate. To actually use the delegate, when calling it, in its parentheses, provide a value for the argument(s) conform to the type specified when declaring the delegate.
Using delegates, a procedure can be indirectly passed as argument to another procedure. To proceed, first declare the necessary delegate. Here is a example of such a delegate: Module Exercise
Delegate Function Squared(ByVal value As Double) As Double
Public Class Circle
Private _radius As Double
Public Property Radius() As Double
Get
Return _radius
End Get
Set(ByVal value As Double)
_radius = value
End Set
End Property
End Class
End Module
A delegate can be passed as argument to a procedure. Such an argument would be used as if it were a procedure itself. This means that, when accessed in the body of the procedure, the name of the delegate must be accompanied by parentheses and if the delegate takes an argument or argument, the argument(s) must be provided in the parentheses of the called delegate. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Delegate Function Squared(ByVal value As Double) As Double
Public Class Circle
Private _radius As Double
Public Property Radius() As Double
Get
Return _radius
End Get
Set(ByVal value As Double)
_radius = value
End Set
End Property
Public Function Area(ByVal sqd As Squared) As Double
Return sqd(_radius) * Math.PI
End Function
End Class
End Module
After declaring a delegate, remember to define a procedure that implements the needed behavior of that delegate. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Delegate Function Squared(ByVal value As Double) As Double
Public Class Circle
Private _radius As Double
Public Property Radius() As Double
Get
Return _radius
End Get
Set(ByVal value As Double)
_radius = value
End Set
End Property
Public Function Area(ByVal sqd As Squared) As Double
Return sqd(_radius) * Math.PI
End Function
End Class
Public Class Exercise
Inherits Form
Public Function ValueTimesValue(ByVal value As Double) As Double
Return value * value
End Function
End Class
End Module
Once the procedure is ready, to associate it to a delegate, declare a variable of the type of the delegate using the New operator. In the parentheses of the constructor, access the name of the associated procedure using the AddressOf operator. To access the delegate, call the Invoke() method. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Delegate Function Squared(ByVal value As Double) As Double
Public Class Circle
Private _radius As Double
Public Property Radius() As Double
Get
Return _radius
End Get
Set(ByVal value As Double)
_radius = value
End Set
End Property
Public Function Area(ByVal sqd As Squared) As Double
Return sqd(_radius) * Math.PI
End Function
End Class
Public Class Starter
Inherits Form
Private lblSide As Label
Private txtSide As TextBox
Private lblArea As Label
Private txtArea As TextBox
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
Dim _side As Double = 46.95
Text = "Circle Calculation"
lblSide = New Label
lblSide.Location = New Point(21, 19)
lblSide.Text = "Side:"
lblSide.AutoSize = True
txtSide = New TextBox
txtSide.Location = New Point(87, 16)
lblArea = New Label
lblArea.Location = New Point(21, 47)
lblArea.Text = "Area:"
lblArea.AutoSize = True
txtArea = New TextBox
txtArea.Location = New Point(87, 44)
Controls.Add(lblSide)
Controls.Add(txtSide)
Controls.Add(lblArea)
Controls.Add(txtArea)
Dim AreaDefinition As Squared = New Squared(AddressOf ValueTimesValue)
txtSide.Text = CStr(_side)
txtArea.Text = CStr(AreaDefinition.Invoke(_side))
End Sub
Public Function ValueTimesValue(ByVal value As Double) As Double
Return value * value
End Function
End Class
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
This would produce:
In a typical application, every class is mostly meant to interact with others, either to request values and methods of the other classes or to provide other classes with some values or a behavior they need. When a class A requests a value or service from another class B, class A is referred to as a client of class B. This relationship is important not simply because it establishes a relationship between both classes but also because class B should be ready to provide the value or behavior that a client needs at a certain time. While a class B is asked to provide some values to, or perform some assignment(s) for, another class A, many things would happen. In fact, there is an order that the actions should follow. For example, during the lifetime of a program, that is, while a program is running, a class may be holding a value it can provide to its client but at another time, that value may not be available anymore, for any reason; nothing strange, this is just the ways it happens. Because different things can happen to a class B while a program is running, and because only class B would be aware of these, it must be able to signal to the other classes when there is a change. This is the basis of events: An event is an action that occurs on an object and affects it in a way that its clients must be made aware of.
An event is declared like a pseudo-variable but based on a delegate. Therefore, to declare an event, you must have a delegate that would implement it. To actually declare an event, you use the Event keyword with the following formula: [modifier] Event Name(Argument) As Type The modifier can be Public, Private, Protected, or Friend. The Event keyword is required. It is followed by the name of the delegate that specifies its behavior. If the event as arguments, enter them in its parentheses. The declaration of an event must specify its type, and the type must be a delegate. Here is an example that declares an event: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Private Delegate Sub Display()
Public Class Starter
Inherits Form
Private Event Evidence As Display
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
End Sub
End Class
End Module
When the event occurs, its delegate would be invoked. This specification is also referred to as hooking up an event. As the event occurs (or fires), the procedure that implements the delegate runs. This provides complete functionality for the event and makes the event ready to be used.
Before using an event, you must specify the procedure that will carry the event. This procedure is referred to as a handler. Obviously you must first have created a procedure. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Private Delegate Sub Display()
Public Class Starter
Inherits Form
Private Event Evidence As Display
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
End Sub
End Class
Private Sub Viewer()
MsgBox("The Viewer")
End Sub
End Module
To add a handler to the program, you use the AddHandler operator with the following formula: AddHandler EventName, AddressOf Procedure The AddHandler and the AddressOf operators are required. The EventName placeholder is used to specify the name of the event that is being dealt with. The Procedure factor is the name of the procedure that will implement the event. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Private Delegate Sub Display()
Public Class Starter
Inherits Form
Private Event Evidence As Display
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
AddHandler Evidence, AddressOf Viewer
End Sub
End Class
Private Sub Viewer()
MsgBox("The Viewer")
End Sub
End Module
After adding a handler for the event, it is ready but you must launch its action. To do this, you can use the RaiseEvent operator with the following formula: RaiseEvent EventName() The RaiseEvent operator is required. The EventName placeholder is used to specify the name of the event, and it must be followed by parentheses. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Private Delegate Sub Display()
Public Class Starter
Inherits Form
Private Event Evidence As Display
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
AddHandler Evidence, AddressOf Viewer
RaiseEvent Evidence()
End Sub
End Class
Private Sub Viewer()
MsgBox("The Viewer")
End Sub
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
The event we used in the previous sections did not take any argument. Just like a delegate, an event can take an argument. The primary rule to follow is that both its delegate and the procedure associated with it must take the same type of event. The second rule is that, when raising the event, you must pass an appropriate event to it. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Private Delegate Sub Display(ByVal Message As String)
Public Class Starter
Inherits Form
Private Event Evidence As Display
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
Dim m As String
m = "Welcome to the wornderful world of events"
AddHandler Evidence, AddressOf Viewer
RaiseEvent Evidence(m)
End Sub
End Class
Private Sub Viewer(ByVal msg As String)
MsgBox(msg)
End Sub
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
Just like an event can take an argument, it can also take more than one argument. The primary rules are the same as those for a single parameter. You just have to remember that you are dealing with more than one argument. Here is an example: Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Private Delegate Sub Description(ByVal Name As String, _
ByVal Salary As Double)
Public Class Starter
Inherits Form
Private Event Recorder As Description
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
Dim FullName As String
Dim HourlySalary As Double
FullName = "Paul Bertrand Yamaguchi"
HourlySalary = 24.55
AddHandler Recorder, AddressOf ShowRecord
RaiseEvent Recorder(FullName, HourlySalary)
End Sub
End Class
Private Sub ShowRecord(ByVal id As String, ByVal wage As Double)
MsgBox("Employee Name: " & id & vbCrLf & _
"Hourly Salary: " & CStr(wage))
End Sub
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module
Instead of a parameter of a primitive type, you can create an event that takes a class as argument.
An application is made of various objects or controls. During the lifetime of an application, its controls regularly send messages to the operating system to do something. These messages are similar to human messages and must be processed appropriately. Since most of the time more than one application is running on the computer, the controls of such an application also send messages to the operating system. As the operating system is constantly asked to perform these assignments, because there can be so many requests presented unpredictably, the operating system leaves it up to the controls to specify what they want, when they want it, and what behavior or result they expect. These scenarios work by the controls sending events. Events in the .NET Framework are implements through the concepts of delegates and events as reviewed previously. The most common events have already been created for the objects of the .NET Framework controls so much that you will hardly need to define new events. Most of what you will do consists of implementing the desired behavior when a particular event fires. To start, you should know what events are available, when they work, how they work, and what they produce. To process a message, it (the message) must provide at least two pieces of information: What caused the message and what type of message is it? Both values are passed as the arguments to the event. Since all controls used in the .NET Framework are based on the Object class, the first argument must be an Object type and represents the control that sent the message. As mentioned already, each control sends its own messages when necessary. Based on this, some messages are unique to some controls according to their roles. Some other messages are common to various controls, as they tend to provide similar actions. To manage such various configurations, the .NET Framework considers the messages in two broad categories. As it happens, in order to perform their intended action(s), some messages do not require much information. For example, suppose your heart sends a message to the arm and states, “Raise your hand”. In this case, suppose everything is alright, the arm does not ask, “how do I raise my hand?”. It simply does because it knows how to, without any assistance. This type of message would be sent without much detailed information. In the .NET Framework, a message that does not need particular information is carried by a class named EventArgs. In the event implementation, an EventArgs argument is passed as the second parameter. Consider another message where the arm carries some water and says to the mouth, “Swallow the following water”. The mouth would need the water that needs to be swallowed. Therefore, the message must be accompanied by additional information. Consider one more message where the heart says to the tongue, “Taste the following food but do not swallow it.” In order to process this message, the tongue would need the food and something to indicate that the food must not be swallowed. In this case, the message must be accompanied by detailed pieces of information. When a message must carry additional information, the control that sent the message specifies that information by the name of the second argument. Because there are various types of messages like that, there are also different types of classes used to carry such messages. We will introduce each class when appropriate.
Although there are different means of implementing an event, there are two main ways you can initiate its coding. If the control has a default event and if you double-click it, the designer would initiate the default event and open the Code Editor. The cursor would be positioned in the body of the event, ready to receive your instructions. As another technique, display the form and click either
the body of the form or a control on it. Then, on the Properties window,
click the Events button
Another alternative you can use consists of displaying the form, right- clicking the form and clicking View Code. Then, in the Class Name combo box, select the name of the control:
In the Method Name combo box, select the event you want to implement:
While an application is opening on the screen or it needs to be shown, the operating system must display its controls. To do this, the controls colors and other visual aspects must be retrieved and restored. This is done by painting the control. If the form that hosts the controls was hidden somewhere such as behind another window or was minimized, when it comes up, the operating system needs to paint it (again). When a control gets painted, it fires the Paint() event. The syntax of the Paint() event is: Private Sub Control_Paint(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.PaintEventArgs) _
Handles MyBase.Paint
End Sub
This event is carried by a PaintEventHandler delegate declared as follows: Public Delegate Sub PaintEventHandler ( _ sender As Object, _ e As PaintEventArgs _ ) The PaintEventArgs parameter provides information about the area to be painted and the graphics object to paint.
When using an application, one of the actions a user can perform on a form or a control is to change its size, provided the object allows it. Also, some time to time, if possible, the user can minimize, maximize, or restore a window. Whenever any of these actions occur, the operating system must keep track of the location and size of a control. For example, if a previously minimized or maximized window is being restored, the operating system must remember where the object was previously positioned and what its dimensions were. When the size of a control has been changed, it fires the Resize() event, which is a EventArgs type.
A keyboard is a hardware object attached to the computer. By default, it is used to enter recognizable symbols, letters, and other characters on a control. Each key on the keyboard displays a symbol, a letter, or a combination of those, to give an indication of what the key could be used for. The user typically presses a key, which sends a signal to a program. The signal is analyzed to find its meaning. If the program or control that has focus is equipped to deal with the signal, it may produce the expected result. If the program or control cannot figure out what to do, it ignores the action. Each key has a code that the operating system can recognize.
When a keyboard key is pressed, a message called KeyDown is sent. KeyDown is a KeyEventArgs type interpreted through the KeyEventHandler event whose syntax is: Public Event KeyDown As KeyEventHandler The KeyEventHandler event is carried by the KeyEventArgs class defined in the System.Windows.Forms namespace through the KeyEventHandler delegate: Public Delegate Sub KeyEventHandler(sender As Object, e As KeyEventArgs) When you initiate this event, its KeyEventArgs argument provides as much information as possible to implement an appropriate behavior.
As opposed to the key down message that is sent when a key is down, the KeyUp message is sent when the user releases the key. This event also is of type KeyEventArgs:
When the user presses a key, the KeyPress message is sent. Unlike the other two keyboard messages, the key pressed for this event should (must) be a character key. This event is handled by the KeyPressEventHandler event whose syntax is: Public Event KeyPress As KeyPressEventHandler The KeyPress event is carried by a KeyPressEventArgs class. The Handled property identifies whether this event was handled. The KeyChar property identifies the key that was pressed. It must be a letter or a recognizable symbol. Lowercase alphabetic characters, digits, and the lower base characters such as ; , ‘ [ ] - = / are recognized as they are. For an uppercase letter or an upper base symbols, the user must press Shift + the key. The character would be identified as one entity. This means that the symbol % typed with Shift + 5 is considered as one character.
The mouse is another object that is attached to the computer allowing the user to interact with the machine. The mouse and the keyboard can each accomplish some tasks that are not normally available on the other or both can accomplish some tasks the same way. The mouse is equipped with two, three, or more buttons. When a mouse has two buttons, one is usually located on the left and the other is located on the right. When a mouse has three buttons, one usually is in the middle of the other two. A mouse can also have a round object referred to as a wheel. The mouse is used to select a point or position on the screen. Once the user has located an item, which could also be an empty space, a letter or a word, he or she would position the mouse pointer on it. To actually use the mouse, the user would press either the left, the middle (if any), or the right button. If the user presses the left button once, this action is called Click. If the user presses the right mouse button, the action is referred to as Right-Click. If the user presses the left button twice and very fast, the action is called Double-Click. If the mouse is equipped with a wheel, the user can position the mouse pointer somewhere on the screen and roll the wheel. This usually causes the document or page to scroll up or down, slow or fast, depending on how it was configured.
Before using a control using the mouse, the user must first position the mouse on it. When this happens, the control fires a MouseEnter event. Its syntax is: Public Event MouseEnter As EventHandler This event is carried by an EventArgs argument but does not provide much information, only to let you know that the mouse was positioned on a control.
Whenever the mouse is being moved on top of a control, a mouse event is sent. This event is called MouseMove and is of type MouseEventArgs. Its syntax is: Public Event MouseMove As MouseEventHandler To implement this event, a MouseEventArgs argument is passed to the MouseEventHandler event implementer: Public Delegate Sub MouseEventHandler ( _ sender As Object, _ e As MouseEventArgs) The MouseEventArgs argument provides the necessary information about the event such as what button was clicked, how many times the button was clicked, and the location of the mouse.
If the user positions the mouse on a control and hovers over it, a MouseHover event is fired: Public Event MouseHover As EventHandler This event is carried by an EventArgs argument that does not provide further information than the mouse is hovering over the control.
Imagine the user has located a position or an item on a document and presses one of the mouse buttons. While the button is pressed and is down, a button-down message is sent. This event is called MouseDown: Public Event MouseDown As MouseEventHandler The MouseDown event is of type MouseEventArgs. Like the other mouse move events, the MouseDown event is carried by a MouseEventArgs argument.
After pressing a mouse button, the user usually releases it. While the button is being released, a button-up message is sent and it depends on the button, left or right, that was down. The event produced is MouseUp: Public Event MouseUp As MouseEventHandler Like the MouseDown message, the MouseUp event is of type MouseEventArgs which is passed to the MouseEventHandler for processing.
When the user moves the mouse pointer away from a control, the control fires a MouseLeave event: Public Event MouseLeave As EventHandler
It is possible, but unlikely, that none of the available events featured in the controls of the .NET Framework suits your scenario. If this happens, you can implement your own event. To do this, you should first consult the Win32 documentation to identify the type of message you want to send. There are two main techniques you can use to create or send a message that is not available in a control. You may also want to provide your own implementation of a message.
In order to send a customized version of a Windows message from your control, you must first be familiar with the message. A message in the .NET Framework is based on the Message structure. One of the properties of this structure is Msg. This property holds a constant integer that is the message to send. The constant properties of messages are defined in the Win32 library. To send a message, you can declare a variable of type Message and define it. Once the variable is ready, you can pass it to the DefWndProc() method. Its syntax is: Protected Overridable Sub DefWndProc(ByRef m As Message) To know the various messages available, you can consult the Win32 documentation but you need a way to get the constant value of that message. Imagine you want to send a message to close a form when the user clicks a certain button named Button1. If you have Microsoft Visual Studio (any version) installed in your computer, you can open the WINUSER.H file. In this file, the WM_CLOSE message that carries a close action is defined with the hexadecimal constant 0x0010 ![]() You can then define a constant integer in your code and initialize it with this same value.
To process a Windows message that is not available for a control you want to use in your application, you can implement its WndProc() method. Its syntax is: Protected Overridable Sub WndProc(ByRef m As Message) In order to use this method, you must override it in your own class. Once again, you must know the message you want to send. This can be done by consulting the Win32 documentation. |
|
|
||
| Previous | Copyright © 2008-2009, yevol.com | Next |
|
|
||