天天看點

實作VB的DoEvents函數(VC++)

在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
			);      
最後一句話:如果是長時間循環處理,使用多線程!