MFC常用操作总结

摘要:
“);}用于{TRACE;}//获取保存的文件名TCHARszFilter[]=_ T;CFileDialogsaveFileDlg;saveFileDlg。m_纳米。lpstrTitle=_ T;//如果{CStringfilePath=saveFileDlg.GetPathName();SetDlgItemText;}//,则可以设置对话框的标题创建多级目录CStringdirPath=_ T,tmpDir;intstartPos=目录路径。发现而(startPos!=-1){tmpDir=dirPath.Left;BOOLisOk=CreateDirectory;startPos=dirPath.Find;}//在指定文件夹voidFindFileInDir{CFileFindfinder;CStringtmpFindName;if(fileType.Find(_T(“.”))下查找特定类型的文件!
// 获取文件基本属性
#if 0
    CFile成员:
    BOOL GetStatus(CFileStatus& rStatus) const;
    static BOOL PASCAL GetStatus(LPCTSTR lpszFileName,CFileStatus& rStatus,CAtlTransactionManager* pTM = NULL);
#endif
    CFileStatus fileStatus;
    if (CFile::GetStatus(_T("D:\config.ini"), fileStatus))// 给个目录名也行,如D:\
    {
        TRACE(_T("文件创建时间:%s
"), fileStatus.m_ctime.Format(_T("%Y-%m-%d %H:%M:%S")));
        TRACE(_T("文件修改时间:%s
"), fileStatus.m_mtime.Format(_T("%Y-%m-%d %H:%M:%S")));
        TRACE(_T("最后访问时间:%s
"), fileStatus.m_atime.Format(_T("%Y-%m-%d %H:%M:%S")));
        TRACE(_T("绝对文件名 :%s
"), fileStatus.m_szFullName);
    }
// 选择文件夹
CString folder;
CFolderPickerDialog pickerDialog;
if (pickerDialog.DoModal() == IDOK)
{
    folder = pickerDialog.GetFolderPath();
    TRACE(folder); // Eg: D:dir
}
else
{
    TRACE(_T("dialog canceled"));
}    
// 选择文件
std::vector<CString> selectFiles;
TCHAR szFilter[] = _T("Text Files(*.txt;*.csv)|*.txt; *.csv|Image Files(*.bmp;*.png;*.jpg;*.raw)|*.bmp; *.png; *.jpg; *.raw|All Files (*.*)|*.*||");
CFileDialog openFileDlg(TRUE, // TRUE表示打开
    _T("*.txt"),    // 默认文件扩展名
    NULL,
    OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY /*| OFN_ALLOWMULTISELECT 可以开启多选模式*/, 
    szFilter);
openFileDlg.m_ofn.lpstrTitle = _T("选择图片文件或文本文件");// 可以设置对话框的标题
if (IDOK == openFileDlg.DoModal()) {
    if (openFileDlg.m_ofn.Flags & OFN_ALLOWMULTISELECT) {
        // 多选模式
        POSITION startPos = openFileDlg.GetStartPosition(); // 获取已选择的文件列表的起始位置
        while (startPos != NULL) {
            selectFiles.push_back(openFileDlg.GetNextPathName(startPos));
        }
    }
    else {
        // 单选模式
        selectFiles.push_back(openFileDlg.GetPathName());
    }
}
else {
    TRACE(_T("User cancel select!"));
}

for (auto& filePath : selectFiles) {
    TRACE(filePath);
}
// 获取保存文件名
TCHAR szFilter[] = _T("Text Files(*.txt;*.csv)|*.txt; *.csv||");
CFileDialog saveFileDlg(FALSE/*FileSaveAs*/,
    _T("txt"),    // 默认文件扩展名
    NULL,
    OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT/*文件名已存在时,询问是否覆盖*/,
    szFilter, this);
saveFileDlg.m_ofn.lpstrTitle = _T("文本文件保存");// 可以设置对话框的标题

if (IDOK == saveFileDlg.DoModal()) {
    CString filePath = saveFileDlg.GetPathName();
    SetDlgItemText(IDC_EDIT, filePath);
}
// 创建多级目录
CString dirPath = _T("D:\Te\a\"), tmpDir;
int startPos = dirPath.Find(_T("\"), 0);
while (startPos != -1) {
    tmpDir = dirPath.Left(startPos);
    BOOL isOk = CreateDirectory(tmpDir, NULL);
    startPos = dirPath.Find(_T("\"), startPos + 1);
}
// 查找指定文件夹下的特定类型文件(不查找子文件夹)
void FindFileInDir(const CString& findDir/*D:\Dir\*/, const CString& fileType/*csv*/, std::vector<CString>& vecFindFilePath) 
{
    CFileFind finder;
    CString tmpFindName;
    if (fileType.Find(_T(".")) != -1) {
        tmpFindName = findDir + _T("*") + fileType;
    }
    else {
        tmpFindName = findDir + _T("*.") + fileType;
    }
    BOOL isFind = finder.FindFile(tmpFindName); // start find
    CString findPath;
    while (isFind) {
        isFind = finder.FindNextFile();            // find a file
        if (finder.IsDirectory() || finder.IsDots()) {
            continue;
        }
        else {
            vecFindFilePath.push_back(finder.GetFilePath());
        }
    }
    finder.Close();
}

    //std::vector<CString> vecFind;
    //FindFileInDir(_T("D:\"), _T(".csv"), vecFind);
    //for (auto& elem : vecFind) {
    //    CString strItem = _T("");
    //    strItem.Format(_T("%d"), m_list.GetItemCount());
    //    m_list.InsertItem(m_list.GetItemCount(), strItem);
    //    m_list.SetItemText(m_list.GetItemCount() - 1, 1, elem);
    //}
// CString实现按字符分割功能
std::vector<CString> CMFCOperationTestDlg::CStringSplit(const CString& srcStr, const CString& seperator) { std::vector<CString> vecSubStrs; CString tmpStr = _T(""); int startPos = 0; int endPos = srcStr.Find(seperator, startPos); while (endPos != -1) { tmpStr = srcStr.Mid(startPos, endPos - startPos); tmpStr.Trim(); vecSubStrs.push_back(tmpStr); startPos = endPos + 1; endPos = srcStr.Find(seperator, startPos); } // the last substr tmpStr = srcStr.Mid(startPos, srcStr.GetLength() - startPos); tmpStr.Trim(); vecSubStrs.push_back(tmpStr); return vecSubStrs; } // 测试代码 void InitListControl() { //LONG lStyle; //lStyle = GetWindowLong(m_list.m_hWnd, GWL_STYLE); //获取当前窗口style //lStyle &= ~LVS_TYPEMASK; //清除显示方式位 //lStyle |= LVS_REPORT; //设置style //lStyle |= LVS_SINGLESEL; //单选模式 //SetWindowLong(m_list.m_hWnd, GWL_STYLE, lStyle); //设置style m_list.ModifyStyle(0, LVS_REPORT | LVS_SINGLESEL); DWORD dwStyle = m_list.GetExtendedStyle(); dwStyle |= LVS_EX_FULLROWSELECT; //选中某行使整行高亮(只适用与report风格的listctrl) dwStyle |= LVS_EX_GRIDLINES; //网格线(只适用与report风格的listctrl) dwStyle |= LVS_EX_CHECKBOXES; //item前生成checkbox控件 m_list.SetExtendedStyle(dwStyle); //设置扩展风格 m_list.InsertColumn(0, _T("序号"), LVCFMT_LEFT, 50); // 左对齐 50 m_list.InsertColumn(1, _T("路径"), LVCFMT_LEFT); m_list.SetColumnWidth(1, LVSCW_AUTOSIZE_USEHEADER); // 最后一列自适应宽度 } std::vector<CString> vec = CStringSplit(_T("a, b,c, d, f, e, rryyyu, tyuyuiii, eeeee, eetw,wwerty"), _T(",")); for (int i = 0; i < vec.size(); ++i) { CString strItem = _T(""); strItem.Format(_T("%d"), i + 1); m_list.InsertItem(i, strItem); for (int j = 1; j < m_list.GetHeaderCtrl()->GetItemCount(); ++j) { m_list.SetItemText(i, j, vec.at(i)); } }
// 按行读取文本文件如txt,csv等
BOOL ReadTextFile(const CString& filePath,std::vector<CString>& outData)
{
#if 1
    CStdioFile fileOutput; // 继承自CFile,默认是文本模式
    CFileException ex;

    // Open
    if (!fileOutput.Open(_T("D:\mytest.csv"), 
        CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate | CFile::shareDenyWrite,
        &ex)) {
        // Abort和Close的区别:abort不会抛出异常,即使文件没有打开或者已关闭
        fileOutput.Abort(); // close file safely and quietly

        // ex.ReportError();
        TCHAR szCause[255];
        ex.GetErrorMessage(szCause, 255); // eg: 没有找到文件D:\mytest.csv
        CString strFormatted = _T("The data file could not be opened because of this error: ");
        strFormatted += szCause;
        TRACE(strFormatted);
    }

    // move to file end
    fileOutput.SeekToEnd();

    // Write by line
    for (int i = 0; i < 100; ++i) {
        fileOutput.WriteString(_T("this,is,a,text,file,write,demo
"));
    }

    fileOutput.Close();
#endif

    CStdioFile fileIn;
    CFileException exp;

    // Open
    if (!fileIn.Open(filePath, CFile::modeRead, &exp)) {
        // Abort和Close的区别:abort不会抛出异常,即使文件没有打开或者已关闭
        fileIn.Abort(); // close file safely and quietly
        exp.ReportError(); // if an error occurs, just make a message box

        return FALSE;
    }
    
    // Read
    CString strRead = _T("");
    while (fileIn.ReadString(strRead)) {
#if 1
        // 内容读取到CListCtrl
        int cnt = m_list.GetItemCount(); // 当前列表的行数
        int col = m_list.GetHeaderCtrl()->GetItemCount();// 列数
        CString strItem = _T("");
        strItem.Format(_T("%d"), cnt + 1);
        m_list.InsertItem(cnt, strItem);// 尾部插入行,及第1列内容
        // 剩余的列(当前列表一共2列)
        for (int j = 1; j < col; ++j) {
            m_list.SetItemText(cnt, j, strRead);
        }
#endif
    }

    fileIn.Close();
    return TRUE;
}
// CFile读写二进制文件
bool BinaryFile(LPCTSTR pszSource)
{
    // constructing these file objects doesn't open them
    CFile sourceFile;

    // we'll use a CFileException object to get error information
    CFileException ex;

    // open the source file for reading
    if (!sourceFile.Open(pszSource,
        CFile::modeRead | CFile::shareDenyWrite, &ex))
    {
        // complain if an error happened
        // no need to delete the ex object
        TCHAR szError[1024] = { 0 };
        ex.GetErrorMessage(szError, 1024);
        _tprintf_s(_T("Couldn't open source file: %1024s"), szError);
        TRACE(szError);
        return false;
    }
    else
    {
        BYTE buffer[4096];
        DWORD dwRead;
        do
        {
            dwRead = sourceFile.Read(buffer, 4096);
        } while (dwRead > 0);

        sourceFile.Close();
    }

    return true;

#if 0
    CFile cfile;
    cfile.Open(_T("Write_File.dat"), CFile::modeCreate |
        CFile::modeReadWrite);
    char pbufWrite[100];
    memset(pbufWrite, 'a', sizeof(pbufWrite));
    cfile.Write(pbufWrite, 100);
    cfile.Flush();
    cfile.SeekToBegin();
    char pbufRead[100];
    cfile.Read(pbufRead, sizeof(pbufRead));
    ASSERT(0 == memcmp(pbufWrite, pbufRead, sizeof(pbufWrite)));

    //example for CFile::Remove
    TCHAR* pFileName = _T("Remove_File.dat");
    try
    {
        CFile::Remove(pFileName);
    }
    catch (CFileException* pEx)
    {
        TRACE(_T("File %20s cannot be removed
"), pFileName);
        pEx->Delete();
    }


    // rename file
    TCHAR* pOldName = _T("Oldname_File.dat");
    TCHAR* pNewName = _T("Renamed_File.dat");
    try
    {
        CFile::Rename(pOldName, pNewName);
    }
    catch (CFileException* pEx)
    {
        TRACE(_T("File %20s not found, cause = %d
"), pOldName,
            pEx->m_cause);
        pEx->Delete();
    }
#endif
}

   未完待续。。。

免责声明:文章转载自《MFC常用操作总结》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇解决react下找不到原生高德地图AMap类的问题记录POI导入时单元格下拉框两种实现方式(excel数据有效性)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

MFC浅析(7) CWnd类虚函数的调用时机、缺省实现 .

1. Create2. PreCreateWindow3. PreSubclassWindow4. PreTranslateMessage5. WindowProc6. OnCommand7. OnNotify8. OnChildNotify9. DefWindowProc10. DestroyWindow11. PostNcDestroyCWnd作为MF...

mfc c++ system调用 控制台窗口

c++代码中可以使用system系统调用,很方便,例如我经常用system("copy C:\A\*.txt d:\A"),注意\不能写成/。 将上述语句放在c++代码中,没有问题。程序运行时会弹出控制台窗口。 如果只想使用system功能而不想显示控制台窗口,例如在MFC程序中,可以使用WinExec函数,上述代码可以写成 WinExec("cmd.ex...

MFC中CWnd类及其派生类对话框、消息处理、窗口操作

http://hi.baidu.com/xiaorida21/blog/item/8d8eb77a22eedee52e73b39e.html CWnd类 我们在屏幕上看到的所有对象都和窗口有关,它们或者派生于CWnd,属继承关系,如对话框、工具栏、状态栏、子控件;或者被CWnd合成,属服务员与服务对象关系,如图标、菜单、显示设备。 CWnd类封装的窗口操...

VS2010/MFC编程入门之前言

鸡啄米的C++编程入门系列给大家讲了C++的编程入门知识,大家对C++语言在语法和设计思想上应该有了一定的了解了。但是教程中讲的例子只是一个个简单的例程,并没有可视化窗口。鸡啄米在这套VS2010/MFC编程入门教程中将会给大家讲解怎样使用VS2010进行可视化编程,也就是基于窗口的程序。 C++编程入门系列主要偏重于理论方面的知识,目的是让大家打好底子,...

CFile和CStdioFile的文件读写使用方法

CFile//创建/打开文件CFile file;file.Open(_T("test.txt"),CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite); 文件打开模式可组合使用,用“|”隔开,常用的有以下几种:CFile::modeCreate:以新建方式打开,如果文件不存在,新建;如...

在MFC中使dialog自适应缩放

起因 最近用mfc做了不少小软件,界面上都是基于CDialog或者CFormView,界面不能缩放一直是问题。一个办法是在OnSize()里面调用所有控件的MoveWindow()函数,根据比例调整控件大小。但是在界面上控件比较多的时候,这个发放就显得很繁琐了。于是我写了一个CAutoResize类,去实现控件的统一缩放。 工作原理 原理上很简单,对于MF...