【问题标题】:Windows message pump in infinite loop无限循环中的 Windows 消息泵
【发布时间】:2012-01-28 22:07:45
【问题描述】:

我一直在为游戏制作 Window 类,但消息泵出现问题。

我从 Windows 提供的消息队列中提取事件并将它们发送到它们所属的窗口。这是 Translates 和 Dispatches 的函数。

根据我对 Win32 编程的记忆,翻译和调度消息调用指定的 WindowProc,并使用消息的内容作为参数。所以这里是我指定的 WindowProc...

currWin、currhwnd 和 winMap 被定义为 Window.cpp 的局部变量,位于顶部...

无论如何,调用distributeSystemMessages() 似乎会导致无限循环。

重要提示:游戏循环不在消息处理循环内,消息处理代码也不在其中。消息处理循环应该每帧清空一次消息队列,将每条消息发送到它所属的窗口。

这里是 Window.h...

#ifndef WINDOW_H_INCLUDED
#define WINDOW_H_INCLUDED

#include "SystemMessage.h"
#include <queue>
#include <windows.h>
using namespace std;

///THIS FUNCTION MUST BE CALLED TO GET MESSAGES INTO WINDOW QUEUES
void distributeSystemMessages();

class Window
{
protected:
    HDC hDC;
    HWND hWnd;
    HINSTANCE hInst;
    HGLRC hRC;

public:
    queue<SystemMessage> messages;

    Window(unsigned int width, unsigned int height, const char* name, unsigned int colorBits = 24, unsigned int depthBits = 24, unsigned int stencilBits = 0);
    ~Window();

    void makeContextCurrent();
    void swapBuffers();

    unsigned int getHeight();
    unsigned int getWidth();

    int getMouseX();
    int getMouseY();

    void setSize(unsigned int width, unsigned int height);
};

#endif // WINDOW_H_INCLUDED

这里是 Window.cpp...

#include "Window.h"
#include <map>
#include <cstdio>
#include <GLee.h>
#include <GL/gl.h>
#include <GL/glu.h>
using namespace std;

HWND currhwnd;
Window* currWin;
map<HWND, Window*> winMap = map<HWND, Window*>();

LRESULT CALLBACK MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    if(currhwnd != hwnd)
    {
        map<HWND, Window*>::iterator i = winMap.find(hwnd);
        if(i != winMap.end())
        {
            currWin = (*i).second;
            currhwnd = hwnd;
        }
        else return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }

    SystemMessage msg(hwnd, uMsg, wParam, lParam);

    currWin->messages.push(msg);

    return 0;
}

Window::Window(unsigned int width, unsigned int height, const char* name, unsigned int colorBits, unsigned int depthBits, unsigned int stencilBits)
{
    //TODO: ADD TIME FUNCTIONS TO A TIMER CLASS
    //QueryPerformanceCounter(&startTime);
    //lastTime = startTime;
    messages = queue<SystemMessage>();


    hInst = GetModuleHandle(NULL);

    WNDCLASSEX wincl;        /* Data structure for the windowclass */

    /* The Window structure */
    wincl.hInstance = hInst;
    wincl.lpszClassName = "Squirrel Engine Window";
    wincl.lpfnWndProc = MainWndProc;      /* This function is called by windows */
    wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
    wincl.cbSize = sizeof (WNDCLASSEX);

    /* Use default icon and mouse-pointer */
    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 /* No menu */
    wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
    wincl.cbWndExtra = 0;                      /* structure or the window instance */
    /* Use Windows's default colour as the background of the window */
    wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

    /* Register the window class, and if it fails quit the program */
    if (!RegisterClassEx (&wincl))
    {
        printf("Could not register window class.\n");
        return;
    }

    /* The class is registered, let's create the program*/
    hWnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           "Squirrel Engine Window",/* Classname */
           name,       /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends after on the screen */
           10,                 /* The programs width */
           10,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hInst,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

    RECT rcWindow;
    RECT rcClient;

    GetWindowRect(hWnd, &rcWindow);
    GetClientRect(hWnd, &rcClient);

    POINT ptDiff;
    ptDiff.x = (rcWindow.right - rcWindow.left) - rcClient.right;
    ptDiff.y = (rcWindow.bottom - rcWindow.top) - rcClient.bottom;

    MoveWindow(hWnd,rcWindow.left, rcWindow.top, width + ptDiff.x, height + ptDiff.y, TRUE);

    ShowWindow (hWnd, SW_SHOW);

    hDC = GetDC( hWnd );

    PIXELFORMATDESCRIPTOR pfd;
    ZeroMemory( &pfd, sizeof( pfd ) );
    pfd.nSize = sizeof( pfd );
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL |
                  PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = colorBits;
    pfd.cDepthBits = depthBits;
    pfd.cStencilBits = stencilBits;
    pfd.iLayerType = PFD_MAIN_PLANE;
    int iFormat = ChoosePixelFormat( hDC, &pfd );
    SetPixelFormat( hDC, iFormat, &pfd );

    hRC = wglCreateContext(hDC);
    hDC = hDC;

    //makeContextCurrent();

    winMap[hWnd] = this;
    //TODO: Find out what this function does
    wglSwapIntervalEXT(0);
}

Window::~Window()
{
    wglDeleteContext(hRC);
    ReleaseDC(hWnd, hDC);
    winMap.erase(hWnd);
    PostQuitMessage(0);
}

unsigned int Window::getWidth()
{
    RECT rcClient;
    GetClientRect(hWnd, &rcClient);
    return rcClient.right;
}
unsigned int Window::getHeight()
{
    RECT rcClient;
    GetClientRect(hWnd, &rcClient);
    return rcClient.bottom;
}

void Window::setSize(unsigned int width, unsigned int height)
{
    RECT rcWindow;
    RECT rcClient;

    GetWindowRect(hWnd, &rcWindow);
    GetClientRect(hWnd, &rcClient);

    POINT ptDiff;
    ptDiff.x = (rcWindow.right - rcWindow.left) - rcClient.right;
    ptDiff.y = (rcWindow.bottom - rcWindow.top) - rcClient.bottom;

    MoveWindow(hWnd,rcWindow.left, rcWindow.top, width + ptDiff.x, height + ptDiff.y, TRUE);
}

void Window::makeContextCurrent()
{
    wglMakeCurrent( hDC, hRC );
}

void Window::swapBuffers()
{
    SwapBuffers( hDC );
}

int Window::getMouseX()
{
    POINT p;
    GetCursorPos(&p);

    RECT rcWindow;
    RECT rcClient;

    GetWindowRect(hWnd, &rcWindow);
    GetClientRect(hWnd, &rcClient);

    POINT ptDiff;
    ptDiff.x = (rcWindow.right - rcWindow.left) - rcClient.right;
    ptDiff.y = (rcWindow.bottom - rcWindow.top) - rcClient.bottom;


    return p.x - (rcWindow.left + ptDiff.x);
}
int Window::getMouseY()
{
    POINT p;
    GetCursorPos(&p);

    RECT rcWindow;
    RECT rcClient;

    GetWindowRect(hWnd, &rcWindow);
    GetClientRect(hWnd, &rcClient);

    POINT ptDiff;
    ptDiff.x = (rcWindow.right - rcWindow.left) - rcClient.right;
    ptDiff.y = (rcWindow.bottom - rcWindow.top) - rcClient.bottom;

    return p.y - (rcWindow.top + ptDiff.y);
}

void distributeSystemMessages()
{
    MSG messages;
    while(PeekMessage (&messages, NULL, 0, 0, PM_REMOVE))
    {
        printf("MessageLoop\n");
        TranslateMessage(&messages);
        DispatchMessage(&messages);
    }
}

【问题讨论】:

    标签: c++ winapi window message-queue message-pump


    【解决方案1】:

    通常,您使用对象架构。 Windows 提供对每个 hWnd 的本地空间的访问,这些空间基本上是为了这个确切目的而明确保留供您使用的。您不需要任何全局变量来完成这项工作。

    class Window {
        // Can be virtual if necessary
        LRESULT WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
            // Process the message here
        }
        static LRESULT WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
            if (Window* ptr = reinterpret_cast<Window*>(GetWindowLongPtr(hwnd, GWLP_USERDATA))) {
                return ptr->WindowProc(hwnd, uMsg, wParam, lParam);
            }
            return DefWindowProc(hwnd, uMsg, wParam, lParam);
        }
        HWND hwnd;
    public:
        Window() {
             hwnd = CreateWindowEx(....);
             SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
             ShowWindow(...); // update the ptr
        }
        void ProcessMessages() {
            MSG messages;
            while(PeekMessage (&messages, hwnd, 0, 0, PM_REMOVE))
            {
                printf("MessageLoop\n");
                TranslateMessage(&messages);
                DispatchMessage(&messages);
            }
        }
    };
    

    【讨论】:

    • 您在 CreateWindowEx 中指定了哪个 WindowProc?我一直无法使用对象的方法作为 WindowProc。在这里...我为什么不直接发布整个课程。
    • @Miles:您使用静态 WindowProc。咳咳...我不应该将它们都命名为 WindowProc。我的错。
    • 但是静态WindowProc如何知道将消息发送到哪个窗口的事件队列?这个想法是对消息进行排序。
    • @Miles Rufat-Latre:关键部分是GetWindowLongPtr()SetWindowLongPtr() 方法。使用这两种方法,您可以将指向Window 对象的指针存储到由HWND 标识的操作系统窗口结构中,然后在仅给定HWND 的情况下检索相同的Window 指针。
    • 啊!谢谢!我会使用这个结构,看看它是否得到修复(无限循环可能只是队列使用中的错误)
    猜你喜欢
    • 2012-07-06
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    相关资源
    最近更新 更多