C++打开属性对话框并保持其处于打开状态

#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()
{
    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);
}

另外参考: Reading a contract from the other side: SHSetInstanceExplorer and SHGetInstanceExplorer 

链接是介绍 SHSetInstanceExplorer 的用法

posted @ 2019-10-25 13:43  strive-sun  阅读(439)  评论(0编辑  收藏  举报