Message queue and message processing in Microsoft MFC technology (Part 2)

 

I am Liyuan Breeze. As a veteran in the IT industry for 25 years, today I will talk about the message queue and message processing in Microsoft MFC technology.

In an MFC application, the window sent by the Windows system to the application in the form of a message. After the window receives and processes the message, it returns control to Windows. Windows system can display multiple windows at the same time. This system utilizes message queues to record messages such as mouse and keyboard input to corresponding windows. If the user moves the mouse or taps the keyboard, the device driver for the mouse or keyboard converts the input into messages and puts them in the system message queue. Windows reads messages one at a time from the system queue, removes them from the queue, and then processes them by sending them to the appropriate window procedure.

The message queue is a first-in first-out queue data structure, which is actually an internal linked list in the system kernel. Users can add messages to and read messages from the message queue, and messages are inserted into the queue sequentially. The sending process adds the message to the end of the queue, and the receiving process reads the message from the head of the queue.

Today we will continue with the previous "Message Queue and Message Processing in Microsoft MFC Technology (Part 1)".

Detailed explanation of specific examples - message processing

First, use visual studio 2022 to create a new Win32 application named Win32_message. After the project is built, create a new source file and name it Win32_message.cpp. The function of this program is to create a window, when you press a key on the keyboard, a message box will appear, such as "the value of the character you pressed is 98". If the Backspace key is pressed, once the message is sent successfully, a message box will appear with the prompt sentence "send the back message successfully". Otherwise, other similar message responses such as "failed to send the back message" will appear. Let's take a look at the following code, first look at the entry function WinMain() of this program.

Win32 application entry function example: Win32_message.cpp

//Win32应用程序入口函数WinMain()
int WINAPI WinMain(
  HINSTANCE hInstance,      //指向当前实例的句柄
  HINSTANCE hPrevInstance,      //指向先前实例的句柄
  LPSTR lpCmdLine,      //命令行
  int nCmdShow         //显示状态
)
{
  WNDCLASS wndclass;      //创建一个窗口类 
  wndclass. cbClsExtra=0;     //窗口类无扩展
  wndclass. cbWndExtra=0;    //窗口实例无扩展
  wndclass. hbrBackground=(HBRUSH)GetStockObject (BLACK_BRUSH);  //窗口背景为黑
  wndclass.hCursor=LoadCursor(NULL,IDC_ARROW);    //窗口采用箭头光标
   wndclass. hIcon=LoadIcon(NULL, IDI_APPLICATION);  //窗口的最小化图标为缺省
  wndclass. hInstance=hInstance:  //当前实例句柄
  wndclass. lpfnWndProc=WinHouProc    //定义窗口处理函数
  wndclass.lpszClassName="VC++";      //窗口类为“VC++”
  wndclass.lpszMenuName=NULL;        //窗口无菜单
  wndclass.style=CS_HREDRAW|CS_PARENTDC;          //设置窗口类型
  RegisterClass(&wndclass);        //注册窗口类

  HWND hwnd;
  hwnd=CreateWindow("VC++","消息机制",WS_OVERLAPPEDWINDOW,0,0, 600, 400, NULL, NULL, hInstance, NULL);       //创建窗口

  ShowWindow(hwnd, SW_SHOWNORMAL);         //显示窗口
  UpdateWindow(hwnd);                 //更新窗口

  MSG msg;
  while(GetMessage 6msg, NULL,0,0))       //获取消息
  {
      TranslateMessage (&msg);
      DispatchMessage (&msg);
   }
  return 0;
}

From the code, we can roughly see the operating mechanism of this program. To display a window and execute various commands, a window should be created first. Line 9 corresponds to the step of creating a window class, and line 16 indicates that the function WinHouProc() is assigned to the message response function of this window. Line 20 corresponds to registering the window class, and such a window class has been formed. The next line 23 will define the size, position, window display name and other information of a window. After the window is created, lines 26-27 will display the window and update the status of the window in real time. The last line 30 is to process various messages related to this window, judge whether the message is currently received, and form a loop.

After discussing the entry function, we will introduce the message response function of this window. The code is the message response function WinHouProc() shown below.

Win32 application message response function example: Win32_message.cpp

LRESULT CALLBACK WinHouProc(
  HWND hwnd,          //窗口句柄
  UINT uMsg,          //消息标识符
  WPARAM WParam,      //第一个消息参数
  LPARAM lParam        //第二个消息参数
)
{
  switch(uMsg)
  {
  case WM_CHAR:
      switch(wParam)      //显示所按键值
     {
      case 0x08:         //后退键
           if(PostMessage (hwnd, WM_KEYDOWN, VK_DELETE, 1L))
                MessageBox(hwnd,"发送后退消息成功","VC++",0);
             else
                 MessageBox(hwnd,"发送后退消息失败","VC++",0);
             break;
      default:
            break;
       }
    char szChar[20];
    sprintf(szChar,"所按字符值是%d",wParam);      //转换按键值类型
     MessageBox(hwnd, szChar, "VC++", 0);        //显示按键的值
      break;
   case WM_CLOSE:       //有提示消息的关闭窗口
      if(IDYES=MessageBox(hwnd,"是否结束?","VC++",MB_YESNO)   //判断
           DestroyWindow(hwnd);       //銷毀窗口
      break;
  case WM_DESTROY:                //强制关闭
    PostQuitMessage(0);       //发送关闭消息
    break;
  default:
    return DefWindowProc(hwnd,uMsg,wParam,lParam);     //返回窗口过程
   }
  return 0;
}

The code illustrates 3 functions: display key value, close with prompt message, and force close. Line 14 is the application of the PostMessage() function. If the back message is sent successfully, it will prompt "send back message successfully". Line 31 PostQuitMessage() is a simple form of PostMessage() that delivers a shutdown message.

However, it should be noted that if the program compiled above is run on a version more advanced than VC++6.0 and VS2003, a lot of errors will be reported immediately, and the encoding options of the project should be modified: Project Properties - General - --Character Set - use a multi-byte character set. There will be garbled characters in the denial display text part. Because VC++6.0 and VS2003 use ANSI encoding by default, while VS2022 and above versions use Unicode by default.

About the author: Li Yuan Weifeng, born in 1981, senior engineer, master of engineering from Zhejiang University, software engineering project supervisor, has worked as a programmer, software designer, system architect, early Windows programmer, loyal Visual Studio user, C/C++ user The author is a veteran who has studied, worked hard, and struggled in the computer industry for 25 years. He has experienced the UNIX era, the desktop WIN32 era, the Web application era, the cloud computing era, the mobile phone Android era, the big data era, the ICT era, and AI deep learning Era, the age of intelligent machines, I don't know what era there will be in the future, I just remember that this journey is full of hardships and gains, and I am willing to go on with you, full of hope.

Guess you like

Origin blog.csdn.net/wang2015cn/article/details/131657386