) What is VB event-driven?

Source: Internet
Author: User
You are using the formal or informal VB Program When you hear the event-driven VB... what do you think?
Whatever the answer you think... I will add examples here to explain in detail... in fact, it is very simple, whether you understand the meaning of this word... in fact, you are using it on the first day you open the VB program...

Reprint (www.5201413.com)

Bytes -------------------------------------------------------------------------------------------

The VB program has two working modes: Active Mode and event-driven mode. The active mode is similar to the traditional dos program. After the program is loaded into the system, it will be executed until the end, in event-driven mode, after the program is loaded to the system, the program is temporarily stopped until the event occurs. After the program is run, it will pause the execution and wait for the next event to occur.

Programs in active mode are forbidden under Windows 3.1 because Windows 3.1 is not a real multi-job system, and in order to allow different programs to run at the same time, windows requires that each program call APIs such as yield, getmessage, and peekmessage from time to time (VB calls doevents). When a program calls these functions, windows will take this opportunity to hand over the CPU to other programs, so that every program has the opportunity to use the CPU to achieve the goal of multiple jobs.

However, if a program ignores this rule, it will continue to occupy the CPU, making the entire windows job environment as if it were lost, however, this problem no longer exists after Windows 95 and NT, because Windows 95 and NT have the ability to switch the CPU right of each program, so even if a program enters an infinite loop, Windows will still transfer the CPU usage right to other programs in a short period of time, we can map the relationship between windows and programs to-1:

Although there is no longer a problem under windows, I must emphasize that the event-driven mode is the mainstream of Windows programs. Why? In Windows Multi-job environment, screen output, keyboard input, mouse input... And so on, all of which must be managed by windows. If every program wants to take the initiative to control these output and input devices, it will inevitably lead to confusion, in contrast, the event-driven mode is centered on objects. Program Execution sends objects responsible for different jobs to the Windows work environment. Then these objects will wait for Windows events, then, the events are managed and generated by windows. Therefore, different programs can survive and work together in a Windows environment.

From the perspective of multiple jobs, the event-driven program is also easier to manage. As a result, we reference different objects to process different jobs, therefore, it is relatively difficult to write a program for a job, resulting in difficulties in future debugging and maintenance.

--------------------------------------------------------------------------------
Back from VB events to Windows messages
--------------------------------------------------------------------------------


The above is from the VB point of view, although the author said that Windows will generate events to drive objects, but the more correct statement is that windows first generates a message and is converted to an event Through VB, then drive the object,-2.

Events are generated based on Windows messages.

But how does VB convert messages into events? What is the message? Recall the hwnd (handle of window) we introduced in section 46. It represents the unique identifier of the window, because many objects have the hwnd attribute, therefore, we can map objects to-3, while windows is the object that transmits messages. This allows VB to convert messages into events and then drive the event programs in the objects.

Relationship between objects and windows

How does VB convert messages into events? In Windows, window procedure is the most important thing. It is used to receive messages from windows. When VB creates an object (window, A Windows program is also provided to receive messages from windows, process messages, convert certain messages into events, and then drive the event program of the object, but it is always hidden, therefore, most VB programmers do not know that this number one person exists.

A window program is used to convert a message into an event.


--------------------------------------------------------------------------------
Understanding windows program
--------------------------------------------------------------------------------

For Windows programs, if it is expressed as a VB function, it is as follows:

FunctionWndprocName (byval hwnd as long, byval MSG as long, byval wparam as long,
Byval lparam as long) as long
Select case msg
Case WM _???? 'Message-1
...
Case WM _???? 'Message-2
...
Case else
Ret = defwindowproc (hwnd, MSG, wparam, lparam) end select
WndprocName = RET
End Function

First, let's look at the four parameters of the Windows program:

Hwnd: handle of window. You don't have to explain this!
MSG: the message number, used to indicate the message passed by windows. In the win32api.txt file, we can find many constant definitions starting with WM _ (indicating window message). For example, "Public const wm_lbuttondown = & h201 」, here, the constant symbol (for example, lbuttondown indicates left button down) can make us look at the meaning, while the constant value (& h201) is the number of the message. While the windows program will use if MSG = WM _???? Or select case MSG/case WM _???? To determine whether the received message is a specific message and then process it.
Wparam and lparam: these two parameters are called message parameters. Their meaning varies with the message (parameter 2 MSG). To understand the meaning of each Message Parameter, you must refer to the SDK (Software Development kits) Reference Manual. However, the SDK Reference Manual is very expensive, but you can find the SDK online reference manual in the following two places: (1) VC ++ (2) msdn/CD (Microsoft Developer Network/CD ).

The defwindowproc API function is the most noteworthy function in Windows programs. It is a function provided by windows to reduce the burden on Windows programs, since windows may send hundreds of messages to Windows programs, most of the messages do not need to be specially processed. If you call defwindowproc, you can send the messages to the API for processing.


Windows program provided by VB
--------------------------------------------------------------------------------

If you write your own windows program, you can process the received messages freely. However, in VB Programs, Windows programs are provided by VB, the following describes how the windows program provided by VB processes messages and how events are generated to drive objects.

I have said that there are hundreds of Windows messages. For Windows programs provided by VB, they do not process so many messages. Therefore, in most cases, call defwindowproc for API services. However, all objects provided by VB contain certain events. Therefore, when VB's windows program receives a message, it determines whether the message should be converted into an event, for example, the lbuttondown message should be converted into a mousedown event. If yes, the program will determine whether the event program contains the event (for example, form_mousedown). If yes, the program will be called, see Figure 4 to see how it works.


I think windows and event programs are not very different in concept, however, it is undeniable that VB's windows program will eat a lot of messages (that is to say, these messages will not generate corresponding events). It is not unreasonable for VB to do so, retaining only the most commonly used information can reduce the burden on the program designer. In fact, it can also improve the program execution efficiency. However, since many messages are eaten by VB, VB Programs cannot complete some special functions. In the past, VB was criticized as easy to use but not functional enough, this is an important reason, but this phenomenon has changed significantly since the beginning of VB 5.0. Please continue to read it and I will explain it later.


--------------------------------------------------------------------------------
Give the VB program the callback capability
--------------------------------------------------------------------------------


It is possible to enhance the windows program of VB, but you must first understand the working mode of callback.


In Windows, messages are sent to the Windows program. But what is the transfer? In fact, Windows has prepared the hwnd, MSG, wparam, and lparam parameters, and then calls the functions (Windows program) provided by VB. This is nothing special, however, applications (or VB) call windows, while windows calls windows back to call windows, which is called callback.

To enhance the VB windows program, you must first write the Enhanced Program and set this program to a program that can be callback for Windows, at this time, the most important thing is to tell windows the "Address" of this program, but VB 4.0 and earlier versions cannot obtain the address of the program, therefore, all program designs related to callback are irrelevant to VB Programs. However, after version 5.0, VB provides addressof to describe the addresses of programs that can be obtained by programs, therefore, callback is enabled for the VB program.

Callback program example
--------------------------------------------------------------------------------

Next, let me give you a callback example of the VB program. First, enable the VB online manual (Select the "Description/online manual" in the VB menu), and then find the "addressof" keyword, in the topics found, select addressof sub-examples, and then follow the instructions to transplant the examples to the program, and finally run the program, as a result, this program lists the fonts in the system and displays them in The ListBox of the form,

Addressof example of VB

This example focuses on calling the enumfontfamilies API function (the filllistwithfonts sub-Program of module1). The purpose of enumfontfamilies is to list all fonts of the system, however, the number of system fonts is variable. Therefore, Windows requires that a callback program be passed in to call this function so that Windows can pass the listed fonts to this program one by one, to pass the callback program address to windows, we can find that the parameters of enumfontfamilies are as follows:


Addressof enumfontfamproc

Obtain the enumfontfamproc program address.

--------------------------------------------------------------------------------
Strengthen the windows program of VB
--------------------------------------------------------------------------------

Because VB's windows program is hidden, we cannot change the program code. However, if hwnd is known, Windows allows us to replace existing Windows programs, suppose we want to change the window program preset by form1 to the window program we wrote (assuming the name isWndproc), The called API is as follows:

Ret = setwindowlong (form1.hwnd, GWL _Wndproc, AddressofWndproc)

In this way, the window program preset by VB to form1 will become invalid, insteadWndprocWindows programWndprocTo receive Windows messages.

Window program plug-in Game
--------------------------------------------------------------------------------

The above method is used to change the form's window program. At first glance, it seems to be good, but it is actually dangerous. Why? Think about it. When we want to replace a window program, we should at least provide the same functions as the original window program. We do not know what functions the VB window program provides, the so-called damage is easy to build! To solve this problem, see Figure 6. insert another window program before the original window program to retrieve the information we want to process, in this way, the effect of the original windows program is enhanced. When no messages are processed, call callwindowproc to submit the messages to the original windows program for processing, so that the functions of the original windows program are not damaged. This practice is called subclassing in windows, and the plug-in game in windows. To play the plug-in game, pay attention to some details.

Figure-6 insert another window program before the original window Program

Record the address of the original windows program
--------------------------------------------------------------------------------

Because we have to drop the unprocessed message back to the original window program, the call is:

Ret = setwindowlong (form1.hwnd, GWL _Wndproc, AddressofWndproc)

Before changing the form1 window program, you must record the address of the original window program as follows:

Dim PrevWndprocAs long

PrevWndproc= Getwindowlong (form1.hwnd, GWL _Wndproc)

Returned value: PrevWndprocThat is, the address of the original window program form1.

Writing a program in a window
--------------------------------------------------------------------------------

Assume that the plug-in window program is only for the purpose of the plug-in, but nothing is done after the plug-in, then when the window program receives a message, it calls the original window program, thenWndprocThe windows program is as follows:

FunctionWndproc(Byval hwnd as long, byval MSG as long, byval wparam as long, byval lparam as long) as long

Wndproc= Callwindowproc (prevWndproc, Hwnd, MSG, wparam, lparam)

End Function

It is worth noting that the first parameter of callwindowproc must be passed into the address Prev of the original window program.Wndproc.

If you want to process some messages in the queuing window program, the structure is as follows:

FunctionWndproc(Byval hwnd as long, byval MSG as long, byval wparam as long,
Byval lparam as long) As long SELECT case msg
Case wm_xxxx
... Processes the wm_xxxx Program
Case wm_xxxx
... Processes the wm_xxxx Program
Case else
Wndproc= Callwindowproc (prevWndproc, Hwnd, MSG, wparam, lparam)
End selectend Function

Cancel queue insertion

--------------------------------------------------------------------------------

In the event of line insertion, you must cancel the line insertion before the window ends. Otherwise, the program will be suspended. In this case, you must set the address of the original window program back to form1, as shown below:

Ret = setwindowlong (form1.hwnd, GWL _Wndproc, PrevWndproc)


Instance resolution explanation

--------------------------------------------------------------------------------
Option explicit
Public PrevWndprocAs long

FunctionWndproc(Byval hwnd as long, byval MSG as long, byval wparam as long, byval lparam as long) as long

Debug. Print hwnd, MSG, wparam, lparam

Wndproc= Callwindowproc (prevWndproc, Hwnd, MSG, wparam, lparam)

End Function

There are several things worth noting in this. bas program:

Option explicit description: When writing a program to call a Windows API, it is best to use this description to prohibit the use of unknown variables, because when calling a Windows API, once the data type does not match, errors may occur.
PrevWndprocVariable: used to record the address of the original window program.
Windows program content: In this window program, no messages are processed for the time being. Therefore, callwindowproc is called to send messages to the original window program, and debug is also used. print displays several parameters of the window program to learn how messages are transmitted to the window program.

Option explicit
Private sub form_load ()
Dim RET as long
PrevWndproc= Getwindowlong (Me. hwnd, GWL _Wndproc)
Ret = setwindowlong (Me. hwnd, GWL _Wndproc, AddressofWndproc)
End subprivate sub form_unload (cancel as integer)
Dim RET as long
Ret = setwindowlong (Me. hwnd, GWL _Wndproc, PrevWndproc)
End sub

This. frm Program focuses on the form_load and form_unload event programs. In the form_load event program (that is, when the form is loaded ),Wndproc. BasWndprocThe window program is inserted before the original window program, while the form_unload event program restores the original window program. (Note: to end the program, press the form close button. Do not use the VB end button. Otherwise, form_unload will not be executed)

--------------------------------------------------------------------------------
Enhanced windows program instance
--------------------------------------------------------------------------------

Continue the previousWndproc. VBP program. Let's take a look at two instances that enhance the original windows program of VB.

Disable Windows restoration using wm_queryopen messages
--------------------------------------------------------------------------------

When the wm_queryopen message occurs when the window is restored by "minimization", I want to keep the window in a minimized state using this message. First, assume that we do not use this message, to use VB's existing events to achieve the same purpose, you can write the following program in the form_resize event program:

Private sub form_resize ()
If windowstate <> vbminimized then
Windowstate = vbminimized
End if
End sub

This program can keep the windows in a minimized state, but when the user restores the windows, the windows will be restored first and then reduced, the result shows that the window is restored and then reduced. If we use the wm_queryopen messageWndprocYou only need to modify the windows program as follows:

FunctionWndproc(Byval hwnd as long, byval MSG as long, byval wparam as long,
Byval lparam as long) As long if MSG = wm_queryopen then
'Eat this message and no longer pass it to the original windows program
'That is, do not let the original windows program get the window restoration message.
Else
Wndproc= Callwindowproc (prevWndproc, Hwnd, MSG, wparam, lparam)
End if
End Function

The above program is very simple. As long as the wm_queryopen message occurs, the original windows program will not be called, so that the original windows program does not know that the wm_queryopen message occurs, so it will not be restored by the minimum.

Non-display area mouse events

--------------------------------------------------------------------------------

In existing VB events, only the mouse events in the client rect window are included. When we move the mouse to a non-display area (such as the window title area ), the mousemove event is not received. If we want to move the mouse over the window, the window will become in use. If we simply use the event program to write the program, we will see the following:


Private sub form_mousemove (button as integer, shift as integer, X as single, y as Single)

Me. setfocus

End sub

However, this program is a bit flawed, that is, when the mouse is moved to a non-display area, but not to a display area, the program does not work, in order to allow the program to receive a message that the mouse is moved to a non-display area, we can write the following Windows program:

FunctionWndproc(Byval hwnd as long, byval MSG as long, byval wparam as long,
Byval lparam as long) As long dim RET as long
If MSG = wm_ncmousemove then
Form1.setfocus
End if
Wndproc= Callwindowproc (prevWndproc, Hwnd, MSG, wparam, lparam)
End Function

In the above program, you can determine whether MSG is equal to the wm_ncmousemove message to know whether the user has moved the mouse to a non-display area, because we do not want to change the window behavior, then callwindowproc was called to send the message to the original window program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.