Visual C ++中消息回调函数的执行顺序 [英] Order of execution of message callback function in Visual C++

查看:113
本文介绍了Visual C ++中消息回调函数的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Windows Visual C ++应用程序,该应用程序将监视消息泵的各种事件.这是我的主要cpp文件的框架:

I am in the process of developing a Windows Visual C++ application which will monitor the message pump for various events. Here is a skeleton of my main cpp file:

LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow) {
    HWND hwnd;
    WNDCLASSEX wincl;

    // register WindowProcedure() as message callback function
    wincl.lpfnWndProc = WindowProcedure;
    // assign other properties...

    if (!RegisterClassEx (&wincl))
        return 0;

    // create main window
    hwnd = CreateWindowEx ( ... );

    // infinite message loop
    while (GetMessage (&messages, NULL, 0, 0)) {
        TranslateMessage(&messages);
        DispatchMessage(&messages);
    }

    return 0;
}

这是回调函数的骨架:

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
    switch(message) {
        case WM_CLIPBOARDUPDATE:
            // handle the update here
    }
}

我的简单问题是,是否保证回调函数以序列开始和结束,或者回调函数可能在 parallel 中重叠执行?换句话说,是否可能并行执行两次对回调函数的调用,可能导致竞争状态?还是Windows保证每封邮件一次连续处理一次?欢迎您提供任何文档或参考.

My simple question is whether callback functions are guaranteed to start and end in sequence, or is it possible that they might execute in parallel with some overlapping? In other words, is it possible that 2 calls to the callback function could be executing in parallel, possibly leading to a race condition? Or does Windows guarantee that each message is handled in serial, one at a time? Any documentation or references you might provide would be welcome.

推荐答案

窗口消息存储在队列中.每次调用GetMessage时,它将从队列中删除第一条消息.当您调用DispatchMessage时,将调用您的窗口过程.

Window messages are stored in a queue. Everytime you call GetMessage, it removes the first message from the queue. Your window procedure is called when you call DispatchMessage.

是的,消息是按顺序处理的.但是,如果在窗口过程中调用SendMessage,则可能存在一些重叠,因为该函数绕过消息队列并直接调用窗口过程(与PostMessage则相反,后者只是将消息放入队列中).

So yes, messages are handled in sequence. However, there is some overlapping possible if inside your window procedure you call SendMessage, as that function bypasses the message queue and just calls your window procedure directly (as opposed to PostMessage which just puts the message in the queue).

但这并不意味着窗口过程将并行执行(例如,从多个线程执行). DispatchMessage和SendMessage都不会创建其他线程来运行窗口过程.

But that doesn't mean the window procedure will execute in parallel (as in, from multiple threads). Neither DispatchMessage nor SendMessage will create a different thread to run the window procedure.

这篇关于Visual C ++中消息回调函数的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆