Relatively speaking, the use of events is relatively simple. Before using it, we must first define the event, which means informing Visual Basic what event is called. An event may have its own parameters. For example, a Command button has a Click event, which has no parameters. In addition, the text edit box has a KeyPRess event, which handles related content through a value called "KeyAscii".
To define an event, add code similar to the following to the general declaration section of a class:
Then call the RaiseEvent method in code to fire an event. Just like the following code:
To better illustrate the above process of adding and firing events, let's take an example. First, define an event:
Add the following code in the general declaration section of the CDog class:
Add the Sleep subprocess in the CDog class:
In the code, some useless loops are performed for 1,000,000 times at the beginning. After the computer pauses briefly, the Sleep sub-process triggers the Awake event.
But after the Awake event occurs, should we let the program respond accordingly? Of course, using a command button is easiest, just select the command button object in the list in the code window.
But in that case, we definitely need a control, and everything we see is on the form. Here we purely use the corresponding code and it is invisible.
Of course, using code to receive events requires additional operations:
In the Common Declarations section of the form code window, add the following code:
This code is different from the previous MyDog declaration. It has the keyword WithEvents to inform Visual Basic that the object can receive any event, and the object must receive the event.
Delete all code in the command button; and add the following code in Command1:
The code simply sets MyDog to a new instance of CDog, sets the Name, calls Bark, and finally runs the Sleep subprocess.
Now add some code to respond to the Awake event.
In the Form code window, select "MyDog" from the object drop-down list;
In the "Awake" event of "MyDog", add the following code:
Okay, now it’s time to test.
Press F5 to run the program;
Click the Command button;
In this way, when the puppy barks, he starts to take a nap and is woken up by you at the end. It's amazing!
->