选择文件
#undef UNICODE
#include "windows.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
TCHAR szBuffer[MAX_PATH] = { 0 };
OPENFILENAME file = { 0 };
file.hwndOwner = NULL;
file.lStructSize = sizeof(file);
file.lpstrFilter = "所有文件(*.*)\0*.*\0Exe文件(*.exe)\0*.exe\0";//要选择的文件后缀
file.lpstrInitialDir = "";//默认的文件路径
file.lpstrFile = szBuffer;//存放文件的缓冲区
file.nMaxFile = sizeof(szBuffer) / sizeof(*szBuffer);
file.nFilterIndex = 0;
file.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER;//标志如果是多选要加上OFN_ALLOWMULTISELECT
BOOL bSel = GetOpenFileName(&file);
cout << file.lpstrFile << endl;
return (0);
}
选择文件并需要获取其路径/文件名/扩展名
#undef UNICODE
#include "windows.h"
#include <stdio.h>
#include <cstring>
#include <stdlib.h>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
TCHAR szBuffer[MAX_PATH] = { 0 };
OPENFILENAME file = { 0 };
file.hwndOwner = NULL;
file.lStructSize = sizeof(file);
file.lpstrFilter = "所有文件(*.*)\0*.*\0Exe文件(*.exe)\0*.exe\0";//要选择的文件后缀
file.lpstrInitialDir = "";//默认的文件路径
file.lpstrFile = szBuffer;//存放文件的缓冲区
file.nMaxFile = sizeof(szBuffer) / sizeof(*szBuffer);
file.nFilterIndex = 0;
file.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER;//标志如果是多选要加上OFN_ALLOWMULTISELECT
BOOL bSel = GetOpenFileName(&file);
printf("file: %s", file.lpstrFile);
string filePath = file.lpstrFile; //控制台需要用string,需要包含<string>头文件,并使用using namespace std;
int start = filePath.find_last_of('\\'); //获取最后一个\\的索引
int end = filePath.find_last_of('.'); //获取最后一个.的索引
string filepath = filePath.substr(0, start+1);
string fileName = filePath.substr(start + 1, end - start - 1);
string exten = filePath.substr(end, filePath.length() - end);
}
选择文件夹
#undef UNICODE
#include "windows.h"
#include <ShlObj.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[])
{
TCHAR szPathName[MAX_PATH];
BROWSEINFO bInfo = { 0 };
bInfo.hwndOwner = GetForegroundWindow();//父窗口
bInfo.lpszTitle = TEXT("浏览文件夹");
bInfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_USENEWUI/*包含一个编辑框 用户可以手动填写路径 对话框可以调整大小之类的..*/ |
BIF_UAHINT/*带TIPS提示*/ | BIF_NONEWFOLDERBUTTON /*不带新建文件夹按钮*/;
LPITEMIDLIST lpDlist;
lpDlist = SHBrowseForFolder(&bInfo);
if (lpDlist != NULL)
//if (SHBrowseForFolder(&bInfo))
{
SHGetPathFromIDList(lpDlist, szPathName);
//AfxMessageBox(NULL, szPathName, L"Dir Name", MB_OK);
cout << szPathName << endl;
}
else
{
printf("user cancle\n");
}
return 0;
}