VB.NET Controls Events

By

VB.NET Controls Events


Introduction VB.NET Controls Events


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 on their behalf. 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.
The most commonly sent messages have already been coded in the objects of the .NET Framework controls so much that you will hardly need to define new messages, at least not in the beginning of your Visual Basic programming adventure. Most of what you will do consists of implementing the desired behavior when a particular message is sent. To start, you should know what messages are available, when, and how they work.

Event Implementation


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 studio 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. Another technique you can use consists of displaying the Code Editor. Then, in the Class Name combo box, select the control that will send the message. In the Method Name, select the event that will be fired.

If you dynamically create a control, you must also manually specify how its events would be carried. You should first write a sub procedure that would carry the event. To do this, check the documentation of the event you want to carry; this information lets you know the type of class that carries the event. For example, if you are writing code for a Click event, you would find out that it is carried by an EventArgs class. When writing the sub procedure, you should also use a friendly convention to name the procedure. For example, if you are writing a Click event for a Button control named btnSubmit, the procedure should be named btnSubmit_Clicked. Here is an example:
Private Sub btnSubmit_Clicked(ByVal sender As Object, ByVal e As EventArgs)
        MessageBox.Show("The event was fired")
End Sub
To assign the event to the dynamic control, one of the solutions you can use consists of calling the AddHandler statement. Its syntax is:
AddHandler event, AddressOf eventhandler
To use this statement, attach the name of the event you want to carry to your control. The best way to know the available events is by consulting the documentation of the control you are using. After the event, use the AddressOf expression to specify the name of the procedure that will carry the event. Here is an example:
Public Class Form1
    Inherits System.Windows.Forms.Form
    Dim btnSubmit As Button

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        btnSubmit = New Button
        btnSubmit.Text = "Submit"
        btnSubmit.Location = New Point(200, 20)

        AddHandler btnSubmit.Click, AddressOf btnSubmit_Clicked

        Me.Controls.Add(btnSubmit)

        'Add any initialization after the InitializeComponent() call

    End Sub

    . . . No Change

#End Region

    Private Sub btnSubmit_Clicked(ByVal sender As Object, ByVal e As EventArgs)
        MessageBox.Show("The Click event was fired")
    End Sub
End Class
This would produce:
Handling of a Dynamic Control
 
General Messages

 
Introduction

To process a message, it (the message) must provide at least two pieces of information: Who sent 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, some messages do not require much information to be performed. 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. This type of message would be sent without much detailed information. This type of message is carried by an EventArgs argument passed as the second parameter of the event.
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, which is considered an argument. 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.
 
Control Painting

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.
When a control gets painted, it fires the Paint() event. The syntax of the Paint() event is:
Sub PaintEventHandler(ByVal sender As Object, ByVal e As PaintEventArgs)
This event is a PaintEventArgs type. To process the painting message, a PaintEventArgs argument is passed to the PaintEventHandler delegate. The PaintEventArgs parameter provides information about the area to be painted and the graphics object to paint. 
Control Resizing

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.
Keyboard Messages

 
Introduction

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.
The Key Down Message

When a keyboard key is pressed, a message called KeyDown is sent. KeyDown is a KeyEventArgs type interpreted through the KeyEventHandler class. This event is defined as follows:
Private Sub Object_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown

End Sub
This event is carried by the KeyEventArgs class defined in the System.Windows.Forms namespace. This class is:
Public Class KeyEventArgs
 Inherits EventArgs
    Public Sub New(ByVal KeyData As Keys)
    Public Overridable ReadOnly Property Alt As Boolean
    Public ReadOnly Property Control As Boolean
    Public Property Handled As Boolean
    Public ReadOnly Property KeyCode As Keys
    Public ReadOnly Property KeyData As Keys
    Public ReadOnly Property KeyValue As Integer
    Public ReadOnly Property Modifiers As Keys
    Public Overridable ReadOnly Property Shift As Boolean
End Class
When you initiate this event, its KeyEventArgs argument provides as much information as possible to implement an appropriate behavior.
 
The Key Up Message

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. The event is initiated as follows:
Private Sub Object_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUp

End Sub
Like KeyDown, KeyUp is a KeyEventArgs type.
 
The Key Press Message

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. The event is initiated as follows:
Private Sub Object_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress

End Sub
The KeyPress event is carried by a KeyPressEventArgs type. This class is defined as follows:
Public Class KeyPressEventArgs
   Inherits EventArgs
    Public Sub New(ByVal keyChar As Char)
    Public Property Handled As Boolean
    Public ReadOnly Property KeyChar As Char
End Class
The Handled property identifies whether this event was handled.
The KeyChar property identifies the key that was pressed. It is 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.
 
Mouse Messages

 
Introduction

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.
The Mouse Enter Message

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. This event is initiated as follows:
Private Sub Form1_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.MouseEnter
    
End Sub
This event is carried by an EventArgs argument but doesn't provide much information, only to let you know that the mouse was positioned on a control.
 
The Mouse Move Message

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. It is initiated as follows:
Private Sub Object_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove

End Sub
To implement this event, a MouseEventArgs argument is passed to the MouseEventHandler event implementer. The MouseEventArgs class is defined as follows:
Public Class MouseEventArgs
   Inherits EventArgs
    Public Sub New(ByVal button As MouseButtons, _
                   ByVal clicks As Integer, _
                   ByVal x As Integer, _
                   ByVal y As Integer, _
                   ByVal delta As Integer)
    Public ReadOnly Property Button As MouseButtons
    Public ReadOnly Property Clicks As Integer
    Public ReadOnly Property Delta As Integer
    Public ReadOnly Property X As Integer
    Public ReadOnly Property Y As Integer
End Class
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.
 
The Mouse Hover Message

If the user positions the mouse on a control and hovers over it, a MouseHover event is fired. This event is initiated as follows:
Private Sub Object_MouseHover(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.MouseHover

End Sub
This event is carried by an EventArgs argument that doesn't provide further information than the mouse is hovering over the control.
 
The Mouse Down Message

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 and is of type MouseEventArgs and it is initiated as follows:
Private Sub Object_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown

End Sub
Like the other above mouse move event, the MouseDown event is carried by a MouseEventArgs argument.
 
The Mouse Wheel Message

If a mouse is equipped with a wheel, when the user presses the wheel or starts turning it, a MouseWheel event is fired. You can use this event to specify what would happen if or when the user decides to use the wheel. This event is initiated as follows:
Private Sub Form1_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseWheel

End Sub 
 
The Mouse Up Message

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 and it is initiated as follows:
Private Sub Object_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp

End Sub
Like the MouseDown message, the MouseUp event is of type MouseEventArgs which is passed to the MouseEventHandler for processing.
 
The Mouse Leave Message

When the user moves the mouse pointer away from a control, the control fires a MouseLeave event. This event is initiated as follows:
Private Sub Form1_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.MouseLeave

End Sub
 
Custom Message Implementation

 
Introduction

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.
 
Sending a Custom Windows 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 that is defined as follows:
Public Structure Message
  Public Property HWnd As IntPtr
  Public Property LParam As IntPtr
  Public Property Msg As Integer
  Public Property Result As IntPtr
  Public Property WParam As IntPtr
End 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 C:\Program Files\Microsoft Visual Studio\VC98\Include\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. Here is an example:
Public Class Form1
    Inherits System.Windows.Forms.Form
    Private Const WM_CLOSE As Integer = &H10

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    . . . No Change 

    End Sub

#End Region

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' Declare a variable to hold the message
        Dim Msg As Message

        ' Initialize the Message variable with a handle to the current form,
        Msg.HWnd = Me.Handle
        ' and let the compiler know the type of message you want to send
        Msg.Msg = WM_CLOSE

        ' Once the Message variable is ready, pass it to the DefWndProc() method
        DefWndProc(Msg)
    End Sub
End Class
Creating a Custom Event

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:
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. Here is an example that fires an OnMove event whenever the user tries to move a window; this prevents the user from performing the action:
Public Class Form1
    Inherits System.Windows.Forms.Form
    Private Const WM_MOVE As Integer = &H3
    Declare Auto Function ReleaseTheMouse Lib "user32.dll" _
    Alias "ReleaseCapture" () As Boolean

    Protected Overrides Sub WndProc(ByRef Msg As Message)
        Select Case Msg.Msg
            Case WM_MOVE
                ReleaseTheMouse()
        End Select

        MyBase.WndProc(Msg)
    End Sub

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    . . . No Change

#End Region

End Class

0 comments:

Posting Komentar