這兩天遇見了如何讓CListBox的內容響應鼠標右鍵的問題,沒有頭緒,Google了半天,基本上都是清一色的答復:從clistbox派生一個類,且響應WM_RBUTTONDOWN消息。但起初的實踐發現,這種方法只是讓整個控件響應右鍵,而我想要的是讓其內容響應。
后來才發現是我沒有領悟“答復”的真諦。
為讓CListBox類響應鼠標右鍵,需要從CListBox類派生出一個新類,且在該派生類中添加一個WM_RBUTTONDOWN消息的響應函數,例如如下代碼:
void newlist::OnRButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
MessageBox(_T("Ok,響應鼠標右鍵!"));
CListBox::OnRButtonDown(nFlags, point);
}
以上這段代碼是讓整個listbox空間響應右鍵,為了只讓listbox中的條目響應右擊則需要更改為:
void newlist::OnRButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
int i = GetCurSel();
if(LB_ERR != i)
{
MessageBox("ok");
}
CListBox::OnRButtonDown(nFlags, point);
}
因為當listbox沒有選中內容或多選時,GetCurSel函數返回LB_ERR,于是可以借由GetCurSel函數來實現只讓listbox中的條目響應鼠標右擊,而非整個控件。
P.S: 一旦能夠讓listbox的內容響應右鍵,那么就可以對listbox的內容實現右鍵彈出菜單了,這正我想要的。下附右擊listbox中的內容彈出菜單
void newlist::OnRButtonDown(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息處理程序代碼和/或調用默認值
POINT curpoint;
GetCursorPos(&curpoint);
ScreenToClient(&curpoint);
RECT test;
int i = 0;
while(i<= GetCount())
{
GetItemRect(i, &test);
if (curpoint.y < test.bottom)
{
// 將當前右擊項選中
SetCurSel(i);
// 加載彈出菜單
CMenu temp,*ptr;
temp.LoadMenu(IDR_MENU1);
ptr = temp.GetSubMenu(0);
ClientToScreen(&point);
ptr->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON,point.x,point.y,GetParent());
break;
}
else
// 若之前選中了某項,而現在的右擊又沒有擊中選項,則取消之前的選項
SetCurSel(-1);
i++;
}
CListBox::OnRButtonDown(nFlags, point);
}
posted on 2009-11-30 02:54
zhaoyg 閱讀(3061)
評論(0) 編輯 收藏 引用 所屬分類:
MFC學習筆記