Introduction
How to add a
CFileDialog
, to a Console application.
Background
Sometimes, you would like to Open a text file without the need of an argument for the EXE.
Using the Code
Just add the following code and add the appropriate include files.
In your stdafx.h file.
#pragma once
#define _AFXDLL
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <fstream>
#include <cctype>
#include <conio.h>
#include <iomanip>
#include <afxdlgs.h>
#include <atlstr.h>
The main project file.
#include "stdafx.h"
#include "console.h"
using namespace std;
CString szFileName = "";
CString szFilter = "Text Files(*.txt)|*.txt|All Files(*.*)|*.*";
char ch;
cout << "Open File 'y' or 'Y' ? ";
cin >> ch;
if((ch == 'y') || (ch == 'Y'))
{
CWnd* pWnd = CWnd::FromHandle(GetForegroundWindow());
CFileDialog dlg(TRUE, _T("*.txt"), _T("*.txt"), NULL, szFilter, pWnd);
dlg.m_ofn.Flags |= OFN_FILEMUSTEXIST;
dlg.m_ofn.lpstrTitle = _T("Read a text file");
if(dlg.DoModal() == IDOK)
{
szFileName = dlg.GetPathName();
}
}
cin.get();
if(szFileName.IsEmpty())
{
szFileName = "ReadMe.txt";
}
ifstream in(szFileName, ios::in | ios::binary);
if(!in) {
cout << "Cannot open input file.\n";
cout << "Press any key to Exit!";
while(!_kbhit())
Sleep(2);
return 1;
}
...