Relatively speaking, the use of events is relatively simple. Before use, we must first define the event, which means to notify Visual Basic of what events are 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 editing box has a keypress event, which processes related content using a value named "keyascii.
Defining an event is to add code similar to the following in the General Declaration section of a class:
Public event myeventname (possarguments as string, etc as variant) |
Then, the Code calls the raiseevent method to stimulate an event. Just like the following code:
Raiseevent myeventname ("possargs", "etc ") |
To better illustrate the process of adding and initiating events, we will give an example. First, define an event:
Add the following code in the General Declaration section of the cdog class:
Add the sleep sub-process to the cdog class:
Public sub sleep () Dim I as long For 1 to 1000000 Doevents: doevents Exit Raiseevent awake End sub |
In the Code, some 1000000 useless loops are made at the beginning. After the computer pause for a short time, the sleep subprocess triggers the awake event.
But after the awake event is generated, should we let the program respond accordingly? Of course, using the command button is the simplest, as long as you select the command button object in the code window list.
But in that case, we need a control and all the content we see is in the form. Here we use the corresponding code and it is invisible.
Of course, using code to receive events requires additional operations:
In the General Declaration section of the form code window, add the following code:
Dim withevents mydog as cdog |
This code is different from the previous mydog declaration. It has a keyword withevents to notify Visual Basic that the object can receive any event, and the object must receive the event.
Delete all the code in the command button, and add the following code in command1:
Set mydog = new cdog Mydog. Name = "Billy" Mydog. Bark Mydog. Sleep |
This Code simply sets mydog to a new instance of cdog, sets the name, calls bark, and finally runs the sleep sub-process.
Now add some code to handle the awake event.
In the form code window, select "mydog" from the drop-down list of objects ";
In the "Awake" event of "mydog", add the following code:
Private sub mydog_awake () Msgbox "your pooch has awoken! " End sub |
Now we can test it.
Press F5 to run the program;
Click command;
In this way, when the puppy bark starts to nap, you will be woken up at the end. Amazing!