In Windows applications, a form is created by a special type of thread called UI thread (User Interface thread).
First, the UI thread is a "thread," so it has all the characteristics that a thread should have, such as a thread function and a thread ID.
Second, the "UI thread" is "special" because the UI thread's thread function creates a special object-the form, and is also responsible for creating the various controls on the form.
Forms and controls are familiar, these objects have the ability to receive user action, they are users of the entire application of the media, without such a medium, users can not control the entire application of the operation and stop, often also can not directly see the program's running process and the final results.
So how do forms and controls respond to user actions? Is this response "active" by the form and the controls themselves?
Other words:
Do forms and controls not have the ability to respond independently to user actions, such as keyboard and mouse operations?
The answer is in the negative.
That's weird, like when we clicked a button with the mouse and saw that it was "trapped" and then restored, and then we did see that the program performed the task for this button. is not a button to respond to user action?
This is actually an illusion. The illusion stems from an understanding of the workings of Windows.
Simply put, forms and controls can respond to user actions, and the key is that the UI thread responsible for creating them has a message loop. This message loop is started by the thread function and typically has the following "look" (in C + + code):
MSG msg; //代表一条消息
BOOL bRet;
//从UI线程消息队列中取出一条消息
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
//错误处理代码,通常是直接退出程序
}
else
{
TranslateMessage(&msg); //转换消息格式
DispatchMessage(&msg); //分发消息给相应的窗体
}
}
As you can see, the so-called message loop is actually just a while loop statement.
where the GetMessage () function extracts a message from the message queue, and the contents of the message are filled in to the variable MSG.
The TranslateMessage () function is primarily used to convert wm_keydown and WM_KEYUP messages to WM_CHAR messages.