Windows编程,同一个窗口类,创建两个窗口,销毁两个窗口程序不退出

代码:#defineWIN32_LEAN_AND_MEAN#include<Windows.h>#include<WindowsX.h>#include<string.h... 代码:
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <WindowsX.h>
#include <string.h>

#define WNDCLASS_NAME L"WNDCLASS1"

int giCount = 0;

LRESULT CALLBACK WinProc(
HWND hwnd,
UINT msg,
WPARAM wparam,
LPARAM lparam)
{
PAINTSTRUCT ps;
HDC hdc;

switch(msg)
{
case WM_CREATE:
return 0;
break;
case WM_PAINT:
hdc = BeginPaint(hwnd,&ps);
EndPaint(hwnd,&ps);
return 0;
break;
case WM_DESTROY:
--giCount;
if(giCount == 0)
{
PostQuitMessage(0);
}
return 0;
break;
default:
break;
}
return (DefWindowProc(hwnd,msg,wparam,lparam));
}

int WINAPI WinMain(
HINSTANCE hinstance,
HINSTANCE hprevinstance,
LPSTR lpcmdline,
int ncmdshow)
{
WNDCLASSEX wndcls;
HWND hwnd1;
HWND hwnd2;
MSG msg;

wndcls.cbSize = sizeof(WNDCLASSEX);
wndcls.cbClsExtra = 0;
wndcls.cbWndExtra = 0;
wndcls.hInstance = hinstance;
wndcls.lpfnWndProc = WinProc;
wndcls.style = CS_DBLCLKS | CS_OWNDC | CS_VREDRAW | CS_HREDRAW;
wndcls.lpszClassName = WNDCLASS_NAME;
wndcls.lpszMenuName = NULL;
wndcls.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndcls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndcls.hCursor = LoadCursor(NULL,IDC_ARROW);
wndcls.hIconSm = LoadIcon(NULL,IDI_APPLICATION);

if(!RegisterClassEx(&wndcls))
{
return 0;
}

if(!(hwnd1 = CreateWindowEx(0,
WNDCLASS_NAME,
L"Your First Window",
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
200,200,
400,400,
NULL,
NULL,
hinstance,
NULL)))
{
return 0;
}
++giCount;
if(!(hwnd2 = CreateWindowEx(0,
WNDCLASS_NAME,
L"Your Second Window",
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
200,200,
400,400,
NULL,
NULL,
hinstance,
NULL)))
{
return 0;
}
++giCount;
while(true)
{
if(PeekMessage(&msg,hwnd1,0,0,PM_REMOVE) || PeekMessage(&msg,hwnd2,0,0,PM_REMOVE))
{
if(msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

return msg.wParam;
}
展开
 我来答
lif12347
2013-12-25 · TA获得超过305个赞
知道小有建树答主
回答量:768
采纳率:50%
帮助的人:219万
展开全部
while(true)
{
if(PeekMessage(&msg,hwnd1,0,0,PM_REMOVE) || PeekMessage(&msg,hwnd2,0,0,PM_REMOVE))
{
if(msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
消息循环没结束,再一个你的消息循环有问题呀:

if(PeekMessage(&msg,hwnd1,0,0,PM_REMOVE) || PeekMessage(&msg,hwnd2,0,0,PM_REMOVE)) 返回false的时候就会一直循环下去
追问
当两个窗口都销毁的时候,我在这个函数WinProc,有一个退出消息入队列,那么在
if(PeekMessage(&msg,hwnd1,0,0,PM_REMOVE) || PeekMessage(&msg,hwnd2,0,0,PM_REMOVE)) 这个if语句就会判断到WM_QUIT的消息,为什么进入不了这个break语句呢?
追答
PostQuitMessage 将WM_QUIT 发至线程的消息队列,你的消息只是从hwnd1 和hwnd2 来取,不一定能取到,
while(true)
{
if(PeekMessage(&msg, 0, 0, 0, PM_REMOVE) )
{
if(msg.message == WM_QUIT)
break;

TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
//这样写就对了,不过建议你使用GetMessage来做,这样不会使CPU一个核心达到100%,用PeekMessage一般的情况是做游戏实时渲染
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式