Win32窗口 - 没有关闭消息

时间:2014-09-16 18:50:34

标签: c++ winapi

我目前正在制作一个小的win32窗口包装类,但是我有一些问题。 如果我点击窗口的关闭(X)按钮,窗口立即关闭而不发送退出或销毁消息,因此我不能在关闭窗口之前阻止窗口关闭或保存。 第二个问题/问题是, 如果我使用这个小代码来使用窗口,计算机CPU将得到强有力的使用。 但它只是一个小窗口。 我如何改变/解决这个问题?

int main()
{
    glwCreate();
    while(true/*Later here comes a method that checks, wether window close is requested*/)
    {
        glwUpdate();
    }
    glwDestroy();

    return 0;
}

-

#include "glw.h"


#include <windows.h>
#include <iostream>


HINSTANCE instanceHandle;
WNDCLASSEX windowClass;
HWND windowHandle;


LRESULT CALLBACK WindowMessageHandler(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    std::cout<<uMsg<<'\n';

    switch(uMsg)
    {
        case WM_QUIT:
        {
            std::cout<<"QUIT\n";
            return 0;
        }
        case WM_DESTROY:
        {
            std::cout<<"DESTROY\n";
            return 0;
        }
    }
    return (DefWindowProc(hWnd, uMsg, wParam, lParam));
}


void glwCreate()
{
    instanceHandle = GetModuleHandle(0);

    windowClass.cbSize = sizeof(WNDCLASSEX);
    windowClass.style = CS_HREDRAW | CS_VREDRAW;
    windowClass.lpfnWndProc = WindowMessageHandler;
    windowClass.cbClsExtra = 0;
    windowClass.cbWndExtra = 0;
    windowClass.hInstance = instanceHandle;
    windowClass.hCursor = LoadCursor(0,IDC_ARROW);
    windowClass.hIcon = LoadIcon(0, IDI_APPLICATION);
    windowClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    windowClass.lpszClassName = "atomus_window_class";
    windowClass.lpszMenuName = "menu_name";
    windowClass.hIconSm = LoadIcon(0, IDI_APPLICATION);
    RegisterClassEx(&windowClass);

    windowHandle = CreateWindowEx(  0,
                                    "atomus_window_class",
                                    "atomus title",
                                    WS_OVERLAPPEDWINDOW,
                                    0,
                                    0,
                                    CW_USEDEFAULT,
                                    CW_USEDEFAULT,
                                    0,
                                    0,
                                    instanceHandle,
                                    0);

    ShowWindow(windowHandle, SW_SHOW);
}
void glwDestroy()
{
    DestroyWindow(windowHandle);
    windowHandle = 0;

    UnregisterClass(windowClass.lpszClassName, instanceHandle);
}
void glwUpdate()
{
    MSG message;
    while (PeekMessage (&message, 0, 0, 0, PM_REMOVE) > 0) //Or use an if statement
    {
         TranslateMessage (&message);
         DispatchMessage (&message);
    }
}

1 个答案:

答案 0 :(得分:2)

如果您为WM_CLOSE添加处理,则可以控制窗口是否关闭。如果没有为该消息提供自己的处理,则从DefWindowProc获取默认值,即销毁您的窗口。