CEdit接收文件拖拽很容易(属性"Accept Files"选为true,添加窗体消息OnDropFiles),但ClistCtrl却很难;
CListCtrl添加右键菜单很容易,而CEdit却很难。
这种功能不全面,阴差阳错的感觉让人很头疼。
下面介绍一下 CEdit添加右键菜单 和 CListCtrl接收文件拖拽的方法
1. CEdit 添加右键菜单
从CEdit派生出一个类CMyEdit,添加消息ON_WM_CONTEXTMENU(),响应消息函数OnContextMenu()。如下:
类定义:
//自定义CMyEdit //目的为了实现CEdit添加右键菜单 class CMyEdit : public CEdit { DECLARE_DYNAMIC(CMyEdit) public: CMyEdit(); virtual ~CMyEdit(); DECLARE_MESSAGE_MAP() public: afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); };类实现:
//自定义CMyListCtrl 类 IMPLEMENT_DYNAMIC(CMyEdit, CEdit) BEGIN_MESSAGE_MAP(CMyEdit, CEdit) ON_WM_CONTEXTMENU() //必须要加 END_MESSAGE_MAP() CMyEdit::CMyEdit() { } CMyEdit::~CMyEdit() { } void CMyEdit::OnContextMenu(CWnd* pWnd, CPoint point) { // CG: This block was added by the Pop-up Menu component if (point.x == -1 && point.y == -1) { //keystroke invocation CRect rect; GetClientRect(rect); ClientToScreen(rect); point = rect.TopLeft(); point.Offset(5, 5); } CMenu menu; VERIFY(menu.LoadMenu(IDR_MENU1)); CMenu* pPopup = menu.GetSubMenu(0); ASSERT(pPopup != NULL); CWnd* pWndPopupOwner = this; while (pWndPopupOwner->GetStyle() & WS_CHILD) { pWndPopupOwner = pWndPopupOwner->GetParent(); } pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWndPopupOwner); }
类声明:
//自定义CMyListCtrl //目的为了实现ListCtrl接收文件拖拽 class CMyListCtrl : public CListCtrl { DECLARE_DYNAMIC(CMyListCtrl) public: CMyListCtrl(); virtual ~CMyListCtrl(); DECLARE_MESSAGE_MAP() public: afx_msg void OnDropFiles(HDROP hDropInfo); };
//自定义CMyListCtrl 类 IMPLEMENT_DYNAMIC(CMyListCtrl, CListCtrl) BEGIN_MESSAGE_MAP(CMyListCtrl, CListCtrl) ON_WM_DROPFILES() //必须 END_MESSAGE_MAP() CMyListCtrl::CMyListCtrl() { } CMyListCtrl::~CMyListCtrl() { } //ListCtrl接收拖拽(并且AcceptFiles属性要设为TRUE) void CMyListCtrl::OnDropFiles(HDROP hDropInfo) { // TODO: 在此添加消息处理程序代码和/或调用默认值 ((CUploadAPK*)GetParent())->OnDropFiles(hDropInfo); }
CButton 添加右键菜单同理:
void CRButtonMenuDlg::OnContextMenu(CWnd* /*pWnd*/, CPoint /*point*/) { // TODO: 在此处添加消息处理程序代码 CRect rect; m_button.GetWindowRect(&rect); CPoint p; GetCursorPos(&p);//鼠标点的屏幕坐标 if (rect.PtInRect(p)) { CMenu m_Menu; m_Menu.LoadMenu(IDR_MENU1);//编辑好的菜单资源 CMenu *m_SubMenu = m_Menu.GetSubMenu(0); m_SubMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, p.x, p.y, this); } }