代码实现:

#include <Windows.h> #include <ShlObj.h> #include <atlbase.h> #include <atlcomcli.h> #include

#pragma comment(lib, "ole32.lib")

CString GetExplorerPath() { // Create an instance of IShellWindows CComPtr pShellWindows; HRESULT hr = CoCreateInstance(CLSID_ShellWindows, nullptr, CLSCTX_ALL, IID_PPV_ARGS(&pShellWindows)); if (FAILED(hr)) { return CString(); }

// Enumerate all currently open Explorer windows
VARIANT var;
VariantInit(&var);
var.vt = VT_I4;
IDispatch* pDispatch = nullptr;
CString strPath;
for (var.intVal = 0; pShellWindows->Item(var, &pDispatch) == S_OK; var.intVal++)
{
    // Get the window handle and the current folder in form of a PIDL
    CComPtr<IShellBrowser> pBrowser;
    hr = CComQIPtr<IServiceProvider>(pDispatch)->QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&pBrowser));
    if (FAILED(hr))
    {
        continue;
    }
    HWND hWnd;
    hr = pBrowser->GetWindow(&hWnd);
    if (FAILED(hr))
    {
        continue;
    }
    if (hWnd != GetForegroundWindow())
    {
        continue;
    }
    CComPtr<IShellView> pView;
    hr = pBrowser->QueryActiveShellView(&pView);
    if (FAILED(hr))
    {
        continue;
    }
    CComPtr<IFolderView> pFolderView;
    hr = pView->QueryInterface(IID_PPV_ARGS(&pFolderView));
    if (FAILED(hr))
    {
        continue;
    }
    PIDLIST_ABSOLUTE pidl;
    hr = pFolderView->GetFolder(IID_PPV_ARGS(&pidl));
    if (FAILED(hr))
    {
        continue;
    }

    // Convert the PIDL into a path
    TCHAR szPath[MAX_PATH];
    if (SHGetPathFromIDList(pidl, szPath))
    {
        strPath = szPath;
        CoTaskMemFree(pidl);
        break;
    }
    CoTaskMemFree(pidl);
}

return strPath;

}

int main() { CString strPath = GetExplorerPath(); std::wcout << strPath.GetString() << std::endl; return 0;

c++ 通过win api 如果鼠标点击的是在资源管理器那么输出资源管理器的目录路径包装成一个函数返回路径即可思路Create an instance of IShellWindows and use that to enumerate all currently open Explorer windows Using various related interfaces you can get

原文地址: https://www.cveoy.top/t/topic/hbal 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录