控制台程序弹出选择要打开文件的窗口

#include <Windows.h>
#include "CommDlg.h"
#include "tchar.h"
#include <iostream>

const char* OpenFile()
{
	TCHAR szBuffer[MAX_PATH] = { 0 };
	OPENFILENAME ofn = { 0 };
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = NULL;
	ofn.lpstrFilter = _T("XML file(*.xml)\0*.xml\0");	// 要选择的文件后缀   
	ofn.lpstrInitialDir = _T("");				// 默认的文件路径   
	ofn.lpstrFile = szBuffer;					// 存放文件的缓冲区   
	ofn.nMaxFile = sizeof(szBuffer) / sizeof(*szBuffer);
	ofn.nFilterIndex = 0;

	//标志如果是多选要加上OFN_ALLOWMULTISELECT  
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER;	
	BOOL bSel = GetOpenFileName(&ofn);

	LPWSTR lpwszStrIn = szBuffer;
	LPSTR pszOut = NULL;
	if (lpwszStrIn != NULL)
	{
		int nInputStrLen = wcslen(lpwszStrIn);

		// Double NULL Termination  
		int nOutputStrLen = WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;
		pszOut = new char[nOutputStrLen];		//可能会造成内存泄漏

		if (pszOut)
		{
			memset(pszOut, 0x00, nOutputStrLen);
			WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);
		}
	}
	return pszOut;
}


const bool SelectOpenFiles(char path[])
{
	TCHAR szBuffer[MAX_PATH] = { 0 };
	OPENFILENAME ofn = { 0 };
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = NULL;
	ofn.lpstrFilter = _T("XML file(*.xml)\0*.xml\0");	// 要选择的文件后缀   
	ofn.lpstrInitialDir = _T("");				// 默认的文件路径   
	ofn.lpstrFile = szBuffer;					// 存放文件的缓冲区   
	ofn.nMaxFile = sizeof(szBuffer) / sizeof(*szBuffer);
	ofn.nFilterIndex = 0;
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER;	//标志如果是多选要加上OFN_ALLOWMULTISELECT  
	BOOL bSel = GetOpenFileName(&ofn);
	LPWSTR lpwszStrIn = szBuffer;

	if (lpwszStrIn != NULL)
	{
		int nInputStrLen = wcslen(lpwszStrIn);

		// Double NULL Termination  
		int nOutputStrLen = WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;
		if (path)
		{
			memset(path, 0x00, nOutputStrLen);
			WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, path, nOutputStrLen, 0, 0);

			return true;
		}
	}
	return false;
}



void main()
{
	const char* path = OpenFile();
	std::cout << "path and  file name are " << path <<  std::endl;

	char fileNamePath[256];
	if (SelectOpenFiles(fileNamePath))
		std::cout << "path and  file name are " << fileNamePath << std::endl;

	system("Pause");

}

猜你喜欢

转载自blog.csdn.net/moonlightpeng/article/details/80292287