您的位置:首页 > 其它

vc GetMessage函数不能退出进程问题

2013-12-16 15:04 375 查看
BOOL GetMessage(
LPMSG lpMsg, // message information
HWND hWnd, // handle to window
UINT wMsgFilterMin, // first message
UINT wMsgFilterMax // last message
);


在GetMessage函数的第二个参数是一个窗口句柄,我们知道通常情况下是设为NULL,用于接收属于调用线程的所有窗口的窗口信息,但是如果把他设为创建窗口时返回的那个窗口句柄,那么就会出现CPU占用率为100%的现象,至于为什么呢,先看下面的代码

#include<windows.h>
#include<stdio.h>

LRESULT CALLBACK WinSunProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
);

int WINAPI WinMain(
HINSTANCE hInstance, // handle to current instance
HINSTANCE hPrevInstance, // handle to previous instance
LPSTR lpCmdLine, // command line
int nCmdShow // show state
)
{
WNDCLASS wndclass;
wndclass.cbClsExtra=0;
wndclass.cbWndExtra=0;
wndclass.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH);
wndclass.hCursor=LoadCursor(NULL,IDC_CROSS);
wndclass.hIcon=LoadIcon(NULL,IDI_ERROR);
wndclass.hInstance=hInstance;
wndclass.lpfnWndProc=WinSunProc;
wndclass.lpszClassName="kay&&dan";
wndclass.lpszMenuName=NULL;
wndclass.style=CS_HREDRAW | CS_VREDRAW;

RegisterClass(&wndclass);

//Create the Windows
HWND hwhd;
hwhd=CreateWindow("kay&&dan","My first windows program.",WS_OVERLAPPEDWINDOW,0,50,600,400,NULL,NULL,hInstance,NULL);

//Show and update the Window
ShowWindow(hwhd,SW_SHOWNORMAL);
UpdateWindow(hwhd);

//the Message Recycle
MSG msg;
while(GetMessage(&msg,hwhd,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

return 0;
}

// 窗口过程函数
LRESULT CALLBACK WinSunProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{
switch(uMsg)
{
case WM_CHAR:
char szchar[20];
sprintf(szchar,"char code is %d",wParam);
MessageBox(hwnd,szchar,"Attention",MB_OK);
break;
case WM_LBUTTONDOWN:
MessageBox(hwnd,"mouse click","message",0);
HDC hdc;
hdc=GetDC(hwnd); //不能在响应WM_PAINT消息时调用
TextOut(hdc,50,50,"我的第一个Windows 程序",strlen("我的第一个Windows 程序"));
ReleaseDC(hwnd,hdc);
break;
case WM_PAINT:
HDC hDc;
PAINTSTRUCT ps;
hDc=BeginPaint(hwnd,&ps);
TextOut(hDc,0,50,"重画中。。。",strlen("重画中。。。"));
EndPaint(hwnd,&ps);
break;
case WM_CLOSE:
if(IDYES==MessageBox(hwnd,"是否关闭窗口","消息",MB_YESNO));
{
DestroyWindow(hwnd);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
return 0;
}


在什么的代码中,GetMessage函数的第二个参数,是窗口创建时返回的句柄,当我关闭窗口后 ,去资源浏览器看,是下面的结果



CPU占用率达到100%.原因如下:

GetMessage函数接收到除了WM_QUIT以外的信息均返回非零值,当hWnd参数是无效窗口句柄或者lpMsg参数是无效指针时,会返回-1、当我们关闭窗口时,调用了DestroyWindows来销毁窗口,由于窗口被销毁了,窗口句柄当然就是无效句柄了,那个GetMessage返回-1,在C/C++中非0即真,由于窗口被销毁,GetMessage总是返回-1,所以循环的条件总是为真,于是就形成了死循环,所以CPU使用率会达到100%.


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mfc winapi vc
相关文章推荐