文件和文件夹选择窗口

c++

Posted by YiMiTuMi on July 26, 2019

BROWSEINFO的使用(文件夹的选择)

在应用软件的时候我们经能够看到让我们选择文件夹或安装位置的路径的窗口,主要是通过结构体BROWSEINFO和函数SHBrowseForFolder实现的:

通用:

#include <windows.h>
#include <shlobj.h>
#include <vcl.h>


BROWSEINFO  bi;
bi.hwndOwner = NULL;
bi.pidlRoot = CSIDL_DESKTOP;//文件夹的根目录,此处为桌面
bi.pszDisplayName  = NULL;	
bi.lpszTitle = NULL;//显示位于对话框左上部的提示信息
bi.ulFlags = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;//有新建文件夹按钮
bi.lpfn = NULL; 
bi.iImage = 0;
LPITEMIDLIST pidl = SHBrowseForFolder(&bi);//调用选择对话框
if (pidl == NULL)    
{    
	return strPath;    
}    
TCHAR strFolder[1024];   
SHGetPathFromIDList(pidl,strFolder );

QT实现:

void MainWindow::on_pushButton_clicked()
{
    BROWSEINFO	bInfo = { 0 };
    bInfo.hwndOwner = NULL;
    bInfo.lpszTitle = TEXT("选择路径");
    bInfo.ulFlags = BIF_BROWSEFORCOMPUTER | BIF_DONTGOBELOWDOMAIN|BIF_RETURNONLYFSDIRS;
    LPITEMIDLIST pItemList = ::SHBrowseForFolder(&bInfo);
    TCHAR strFolder[1024];
    SHGetPathFromIDList(pItemList, strFolder);
    ui->label->setText(QString::fromWCharArray(strFolder));
}

增加:

bInfo.ulFlags = BIF_BROWSEINCLUDEFILES; //可以显示文件
bInfo.ulFlags = BIF_NEWDIALOGSTYLE;  //可以调节窗口大小,和新建文件夹按钮

OPENFILENAME的使用(文件的选择)

在使用软件的时候我们经常会看到我们要导入一个文件的窗口,windows对这个窗口的实现进行了封装,通过结构体OPENFILENAME然后通过函数GetOpenFileName来进行调用并获取信息:

QT实现:

#include <windows.h>
#include <commdlg.h>


wchar_t strFile[MAX_PATH];
TCHAR szBuffer[MAX_PATH] = {0};
OPENFILENAME ofn= {0};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
//过滤有问题,可以去掉,也可以自己写
//wstring s = L"所有文件(*.*)\0*.*\0文本文件(*.txt)\0*.txt\0\0";
//ofn.lpstrFilter = s.c_str();
ofn.nMaxFile = MAX_PATH;
ofn.nFilterIndex = 0;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER ;
if (GetOpenFileName(&ofn))
{
   PathStripPathW(strFile);
   filePath = QString::fromWCharArray(strFile);//获取路径
}

windows:

char szFileName[MAX_PATH] = { 0 };
OPENFILENAME openFileName = { 0 };
openFileName.lStructSize = sizeof(OPENFILENAME);
openFileName.nMaxFile = MAX_PATH;  //这个必须设置,不设置的话不会出现打开文件对话框  
openFileName.lpstrFilter = "文本文件(*.txt)\0*.txt\0所有文件(*.*)\0*.*\0\0";
openFileName.lpstrFile = szFileName;
openFileName.nFilterIndex = 1;
openFileName.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

if (::GetOpenFileName(&openFileName))
{
	//::MessageBoxA(hwndDlg, openFileName.lpstrFile, "", MB_OK);
}

格桑花 – 聆取眼前人