2007年12月12日星期三

MFC中消息拦截

Method 1:
BOOL CDbinfoView::PreTranslateMessage(MSG* pMsg)
{
// If edit control is visible in tree view control, when you send a
// WM_KEYDOWN message to the edit control it will dismiss the edit
// control. When the ENTER key was sent to the edit control, the
// parent window of the tree view control is responsible for updating
// the item's label in TVN_ENDLABELEDIT notification code.
if (pMsg->message == WM_KEYDOWN || pMsg->message == WM_LBUTTONDOWN)//pMsg->message == WM_CLOSE)
{
int iID (-1);
switch(pMsg->wParam)
{
case VK_RETURN:

//HWND hWnd=::GetFocus();
//int iID=::GetDlgCtrlID(hWnd);
iID=::GetDlgCtrlID(::GetFocus());

//confirm the message from which Control
if(iID == IDC_EDIT_PATH )
{
//data is being retrieved from DialogForm into FileURL
UpdateData(true);
//Todo:............
}
break;
case VK_TAB:

break;
case VK_LBUTTON:

break;

}

//edit->SendMessage(WM_KEYDOWN, pMsg->wParam, pMsg->lParam);
//return TRUE;

}

// CXxxx can be a CFormView, Cdialog, or CPropertyPage class.
return CWnd::PreTranslateMessage(pMsg);
}


Method 2:

PeekMessage 消息机制
PeekMessage

GetMessage不将控制传回给程序,直到从程序的消息队列中取得消息,但是PeekMessage总是立刻传回,而不论一个消息是否出现。当消息队列中有一个消息时,PeekMessage的传回值为TRUE(非0),并且将按通常方式处理消息。当队列中没有消息时,PeekMessage传回 FALSE(0)。
这使得我们可以改写普通的消息循环。我们可以将如下所示的循环:
while (GetMessage (&msg, NULL, 0, 0))

{

TranslateMessage (&msg) ;

DispatchMessage (&msg) ;

}

return msg.wParam ;


替换为下面的循环:
while (TRUE)

{

if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))

{

if (msg.message == WM_QUIT)

break ;

TranslateMessage (&msg) ;

DispatchMessage (&msg) ;

}

else

{

// 完成某些工作的其它行程序

}

}

return msg.wParam ;


注意,WM_QUIT消息被另外挑出来检查。在普通的消息循环中您不必这么作,因为如果GetMessage接收到一个WM_QUIT消息,它将传回0,但是PeekMessage用它的传回值来指示是否得到一个消息,所以需要对WM_QUIT进行检查。
如果PeekMessage的传回值为TRUE,则消息按通常方式进行处理。如果传回值为FALSE,则在将控制传回给Windows之前,还可以作一点工作(如显示另一个随机矩形)。
(尽管Windows文件上说,您不能用PeekMessage从消息队列中删除WM_PAINT消息,但是这并不是什么大不了的问题。毕竟, GetMessage并不从消息队列中删除WM_PAINT消息。从队列中删除WM_PAINT消息的唯一方法是令窗口显示区域的失效区域变得有效,这可以用ValidateRect和ValidateRgn或者BeginPaint和EndPaint对来完成。如果您在使用PeekMessage从队列中取出WM_PAINT消息后,同平常一样处理它,那么就不会有问题了。所不能作的是使用如下所示的程序代码来清除消息队列中的所有消息:
while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) ;


这行叙述从消息队列中删除WM_PAINT之外的所有消息。如果队列中有一个WM_PAINT消息,程序就会永远地陷在while循环中。)

没有评论: