当前位置: 代码迷 >> 综合 >> C++文件、文件夹选择框(GetOpenFileName,SHBrowseForFolder)
  详细解决方案

C++文件、文件夹选择框(GetOpenFileName,SHBrowseForFolder)

热度:71   发布时间:2023-12-02 19:45:03.0
前言

已有之事,后必再有
已行之事,后比再行

背景:

给Java调用(这也许就是C++吧)

环境:

VS2017

一、选择文件
#include <iostream>
#include <ShlObj.h>
#include <windows.h>
#include <Commdlg.h>void openFileDialog()
{OPENFILENAME ofn;			// 公共对话框结构TCHAR szFile[MAX_PATH];		// 保存获取文件名称的缓冲区   ZeroMemory(&ofn, sizeof(OPENFILENAME));ofn.lStructSize = sizeof(OPENFILENAME);ofn.hwndOwner = NULL;ofn.lpstrFile = szFile;ofn.lpstrFile[0] = '\0';ofn.nMaxFile = sizeof(szFile);ofn.lpstrFilter = L"All\0*.*\0Text\0*.TXT\0Image\0*.PNG;*.JPG\0"; //过滤规则ofn.nFilterIndex = 1;ofn.lpstrFileTitle = NULL;ofn.nMaxFileTitle = 0;ofn.lpstrInitialDir = L"C:\\Program Files";	//指定默认路径ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;if (GetOpenFileName(&ofn)){//显示选择的文件。 wchar_t * t = ofn.lpstrFile;// 将wchar_t转化为char输出std::cout << wcharTochar(t) << std::endl;}
}char * wcharTochar(const wchar_t * _wchar)
{char * _char;int len = WideCharToMultiByte(CP_ACP, 0, _wchar, (int)wcslen(_wchar), NULL, 0, NULL, NULL);_char = new char[len + 1];WideCharToMultiByte(CP_ACP, 0, _wchar, (int)wcslen(_wchar), _char, len, NULL, NULL);_char[len] = '\0';return _char;
}
二、选择文件夹
void openFolderDialog()
{TCHAR path[MAX_PATH] = { 0 };BROWSEINFO bi;bi.hwndOwner = 0;bi.pidlRoot = NULL;bi.pszDisplayName = path;bi.pszDisplayName[0] = '\0';bi.ulFlags = BIF_RETURNONLYFSDIRS;bi.lpfn = NULL;bi.lParam = 0;bi.iImage = 0;LPMALLOC pMalloc;LPITEMIDLIST pidl;pidl = SHBrowseForFolder(&bi);if (pidl != NULL){SHGetPathFromIDList(pidl, path);wchar_t * qsFile = bi.pszDisplayName;if (SUCCEEDED(SHGetMalloc(&pMalloc))){pMalloc->Free(pidl);pMalloc->Release();}std::cout << wcharTochar(qsFile) << std::endl;}
}
需要注意的地方
  1. 输出注意编码问题
  2. 选择文件设置过滤规则,传参时需要将char *转wchar_t *,但是\0在C++中为空格,在转化过程中会自动截断,在转化过程中需要注意