创建上下文菜单项
1、新建一个ATL Project。
2、建议将Project Property中Linker – General - “Register Output” 设为no,C/C++ - “Code Generation” - “Runtime Library” 设为 /MTd。
3、在Solution Explorer中右键Add Class,选择ATL Simple Object。并在弹出的对话框中为该Class命名。
4、添加完成后建议Build一下Project,MIDL compiler将根据 .idl文件生成IIDs and CLSIDs。
5、(可选)在Solution Explorer中右键Add Resource导入图标资源。
6、切换到新增Class的 .h文件中,使其继承接口IShellExtInit和IContextMenu。并在 .cpp文件中,参照MSDN给出实现。
1 // MyContextMenu.h : Declaration of the CMyContextMenu 2 3 #pragma once 4 #include "resource.h" // main symbols 5 6 7 8 #include "ContextMenuExample_i.h" 9 #include <Shlobj.h> 10 11 12 13 #if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA) 14 #error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms." 15 #endif 16 17 using namespace ATL; 18 19 20 // CMyContextMenu 21 22 class ATL_NO_VTABLE CMyContextMenu : 23 public CComObjectRootEx<CComSingleThreadModel>, 24 public CComCoClass<CMyContextMenu, &CLSID_MyContextMenu>, 25 public IDispatchImpl<IMyContextMenu, &IID_IMyContextMenu, 26 &LIBID_ContextMenuExampleLib, /*wMajor =*/ 1, /*wMinor =*/ 0>, 27 public IShellExtInit, 28 public IContextMenu 29 { 30 public: 31 CMyContextMenu() 32 { 33 } 34 35 DECLARE_REGISTRY_RESOURCEID(IDR_MYCONTEXTMENU) 36 37 38 BEGIN_COM_MAP(CMyContextMenu) 39 COM_INTERFACE_ENTRY(IMyContextMenu) 40 COM_INTERFACE_ENTRY(IDispatch) 41 COM_INTERFACE_ENTRY(IShellExtInit) 42 COM_INTERFACE_ENTRY(IContextMenu) 43 END_COM_MAP() 44 45 46 47 DECLARE_PROTECT_FINAL_CONSTRUCT() 48 49 HRESULT FinalConstruct(); 50 51 void FinalRelease(); 52 53 public: 54 // IShellExtInit Method 55 HRESULT STDMETHODCALLTYPE Initialize( 56 _In_opt_ PCIDLIST_ABSOLUTE pidlFolder, 57 _In_opt_ IDataObject *pdtobj, 58 _In_opt_ HKEY hkeyProgID); 59 60 // IContextMenu Method 61 HRESULT STDMETHODCALLTYPE QueryContextMenu( 62 _In_ HMENU hmenu, 63 _In_ UINT indexMenu, 64 _In_ UINT idCmdFirst, 65 _In_ UINT idCmdLast, 66 _In_ UINT uFlags); 67 68 HRESULT STDMETHODCALLTYPE InvokeCommand( 69 _In_ CMINVOKECOMMANDINFO *pici); 70 71 HRESULT STDMETHODCALLTYPE GetCommandString( 72 _In_ UINT_PTR idCmd, 73 _In_ UINT uType, 74 _Reserved_ UINT *pReserved, 75 _Out_writes_bytes_((uType & GCS_UNICODE) ? (cchMax * sizeof(wchar_t)) : cchMax) _When_(!(uType & (GCS_VALIDATEA | GCS_VALIDATEW)), _Null_terminated_) CHAR *pszName, 76 _In_ UINT cchMax); 77 78 private: 79 HBITMAP MenuIcon1; 80 HBITMAP MenuIcon2; 81 HBITMAP MenuIcon3; 82 HBITMAP MenuIcon4; 83 84 85 }; 86 87 OBJECT_ENTRY_AUTO(__uuidof(MyContextMenu), CMyContextMenu)