如何在C++中打开文件资源管理器对话框?

e0bqpujr  于 2023-11-19  发布在  其他
关注(0)|答案(2)|浏览(258)

我正在用C的ImGui开发一个桌面应用程序,我需要用户能够用文件浏览器在他们的机器上搜索文件。用Python tkinter非常容易做到,但我怎么能用C做到这一点呢?

bzzcjhmw

bzzcjhmw1#

你可以使用NativeFileDialog,它很容易实现,他们在GitHub上也有一个例子!

pxq42qpu

pxq42qpu2#

本机Windows解决方案:这将打开“Windows文件选择”提示符,我将其包含在一个自定义函数中,该函数还将结果和文件名存储到字符串变量中。
我使用一个变种的包括方法为我的自定义前端启动器。希望你使一些使用它,即使你问这个问题9个月前

#include <Windows.h>
#include <string>
#include <shobjidl.h> 

std::string sSelectedFile;
std::string sFilePath;
bool openFile()
{
    //  CREATE FILE OBJECT INSTANCE
    HRESULT f_SysHr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (FAILED(f_SysHr))
        return FALSE;

    // CREATE FileOpenDialog OBJECT
    IFileOpenDialog* f_FileSystem;
    f_SysHr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL, IID_IFileOpenDialog, reinterpret_cast<void**>(&f_FileSystem));
    if (FAILED(f_SysHr)) {
        CoUninitialize();
        return FALSE;
    }

    //  SHOW OPEN FILE DIALOG WINDOW
    f_SysHr = f_FileSystem->Show(NULL);
    if (FAILED(f_SysHr)) {
        f_FileSystem->Release();
        CoUninitialize();
        return FALSE;
    }

    //  RETRIEVE FILE NAME FROM THE SELECTED ITEM
    IShellItem* f_Files;
    f_SysHr = f_FileSystem->GetResult(&f_Files);
    if (FAILED(f_SysHr)) {
        f_FileSystem->Release();
        CoUninitialize();
        return FALSE;
    }

    //  STORE AND CONVERT THE FILE NAME
    PWSTR f_Path;
    f_SysHr = f_Files->GetDisplayName(SIGDN_FILESYSPATH, &f_Path);
    if (FAILED(f_SysHr)) {
        f_Files->Release();
        f_FileSystem->Release();
        CoUninitialize();
        return FALSE;
    }

    //  FORMAT AND STORE THE FILE PATH
    std::wstring path(f_Path);
    std::string c(path.begin(), path.end());
    sFilePath = c;

    //  FORMAT STRING FOR EXECUTABLE NAME
    const size_t slash = sFilePath.find_last_of("/\\");
    sSelectedFile = sFilePath.substr(slash + 1);

    //  SUCCESS, CLEAN UP
    CoTaskMemFree(f_Path);
    f_Files->Release();
    f_FileSystem->Release();
    CoUninitialize();
    return TRUE;
}

bool result = FALSE;
int main()
{
    result = openFile();
    switch (result) {
        case(TRUE): {
            printf("SELECTED FILE: %s\nFILE PATH: %s\n\n", sSelectedFile.c_str(), sFilePath.c_str());
            system("pause");
        }
        case(FALSE): {
            printf("ENCOUNTERED AN ERROR: (%d)\n", GetLastError());
            system("pause");
        }
    }
    return 0;
}

字符串

相关问题