以下是实现代码:

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

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

char** GetExplorerDirectory() {
    char** result = nullptr;

    // Create an instance of IShellWindows
    CComPtr<IShellWindows> spShellWindows;
    HRESULT hr = spShellWindows.CoCreateInstance(CLSID_ShellWindows);
    if (FAILED(hr)) {
        return result;
    }

    // Enumerate all windows
    long count = 0;
    hr = spShellWindows->get_Count(&count);
    if (FAILED(hr)) {
        return result;
    }

    for (long i = 0; i < count; i++) {
        CComVariant index(i);
        CComPtr<IDispatch> spDispatch;
        hr = spShellWindows->Item(index, &spDispatch);
        if (FAILED(hr)) {
            continue;
        }

        CComPtr<IServiceProvider> spServiceProvider;
        hr = spDispatch->QueryInterface(IID_IServiceProvider, (void**)&spServiceProvider);
        if (FAILED(hr)) {
            continue;
        }

        CComPtr<IShellBrowser> spShellBrowser;
        hr = spServiceProvider->QueryService(SID_STopLevelBrowser, IID_IShellBrowser, (void**)&spShellBrowser);
        if (FAILED(hr)) {
            continue;
        }

        HWND hwnd = nullptr;
        hr = spShellBrowser->GetWindow(&hwnd);
        if (FAILED(hr) || hwnd == nullptr) {
            continue;
        }

        // Check if the window is currently focused
        if (hwnd != GetForegroundWindow()) {
            continue;
        }

        CComPtr<IShellView> spShellView;
        hr = spShellBrowser->QueryActiveShellView(&spShellView);
        if (FAILED(hr)) {
            continue;
        }

        CComPtr<IFolderView> spFolderView;
        hr = spShellView->QueryInterface(IID_IFolderView, (void**)&spFolderView);
        if (FAILED(hr)) {
            continue;
        }

        PIDLIST_ABSOLUTE pidl = nullptr;
        hr = spFolderView->GetFolder(IID_PPV_ARGS(&pidl));
        if (FAILED(hr)) {
            continue;
        }

        // Convert the PIDL to a path
        WCHAR szPath[MAX_PATH] = { 0 };
        SHGetPathFromIDList(pidl, szPath);
        CoTaskMemFree(pidl);

        // Allocate memory for the result
        result = new char*[2];
        result[0] = new char[strlen(szPath) + 1];
        result[1] = nullptr;

        // Copy the path to the result
        wcstombs(result[0], szPath, strlen(szPath) + 1);

        break;
    }

    return result;
}

该函数返回一个char**类型的指针,其中第一个元素是资源管理器当前目录的路径,第二个元素为nullptr。如果无法获取路径,则该函数返回nullptr。

使用示例:

char** path = GetExplorerDirectory();
if (path != nullptr) {
    printf("Explorer directory: %s\n", path[0]);
    delete[] path[0];
    delete[] path;
}
``

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

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