在VC++中,碰到了比如等待通讯数据等需要很长时间的循环时,在循环里加入类似VB的DoEvents函数,使画面一直处于事件响应状态。实际上,DoEvents函数的内容就是一个窗口消息处理环。
void DoEvents()
{
MSG msg;
while(::PeekMessage(&msg, NULL, NULL, NULL, PM_NOREMOVE))
{
if (!AfxGetApp()->PumpMessage())
return;
}
}
或
void DoEvents()
{
MSG msg;
while (::GetMessage(&msg, NULL, NULL, NULL))
{
if (!PreTranslateMessage(&msg))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
}
注意点:这种方法在长时间的循环処理中能不断进行画面操作,可以说这个DoEvents手法还是挺方便的。可是在DoEvents()中,
任何Windows的消息多可能被处理,有时出现了预料不到的结果。所以,尽可能使用下面函数中的wMsgFilterMin和wMsgFilterMax参数,
对处理的消息种类作适当制限,编出更加安全的DoEvents()。
BOOL PeekMessage( LPMSG lpMsg, // pointer to structure for message
HWND hWnd, // handle to window
UINT wMsgFilterMin, // first message
UINT wMsgFilterMax, // last message
UINT wRemoveMsg // removal flags
);
BOOL GetMessage( LPMSG lpMsg, // address of structure with message
HWND hWnd, // handle of window
UINT wMsgFilterMin, // first message
UINT wMsgFilterMax // last message
);
最后一句话:如果是长时间循环处理,使用多线程!