用到ShellExecuteEx
为了防止属性对话框无法成功打开(程序运行太快,以至于没有时间打开属性对话框,程序就结束了)
调用SHSetInstanceExplorer
并使其保持活动状态,直到该COM对象被释放:
#include <windows.h> #include <shlobj_core.h> #pragma comment(lib,"Shell32.lib") class ProcessReference : public IUnknown { public: STDMETHODIMP QueryInterface(REFIID riid, void **ppv) { if (riid == IID_IUnknown) { *ppv = static_cast<IUnknown*>(this); AddRef(); return S_OK; } *ppv = NULL; return E_NOINTERFACE; } STDMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&m_cRef); } STDMETHODIMP_(ULONG) Release() { LONG lRef = InterlockedDecrement(&m_cRef); if (lRef == 0) PostThreadMessage(m_dwThread, WM_NULL, 0, 0); return lRef; } ProcessReference() : m_cRef(1), m_dwThread(GetCurrentThreadId()) { SHSetInstanceExplorer(this); } ~ProcessReference() { SHSetInstanceExplorer(NULL); Release(); MSG msg; while (m_cRef && GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } } private: LONG m_cRef; DWORD m_dwThread; }; int main(void) { struct CoInit { HRESULT m_hr; CoInit() { m_hr = CoInitialize(0); } ~CoInit() { if (SUCCEEDED(m_hr)) CoUninitialize(); } } coinit; ProcessReference ref; IShellItem*pSI; HRESULT hr = SHCreateItemInKnownFolder(FOLDERID_Windows, KF_FLAG_DEFAULT, L"Explorer.exe", IID_IShellItem, (void**)&pSI); if (hr) return hr; IContextMenu*pCM; hr = pSI->BindToHandler(NULL, BHID_SFUIObject, IID_IContextMenu, (void**)&pCM); pSI->Release(); if (hr) return hr; SHELLEXECUTEINFO info = { 0 }; info.cbSize = sizeof info; info.lpFile = "C:\\Users\\strives\\Desktop\\print.txt"; info.nShow = SW_SHOW; info.fMask = SEE_MASK_INVOKEIDLIST; info.lpVerb = "properties"; ShellExecuteEx(&info); }