目前共有3篇帖子。 內容轉換:不轉換▼
 
點擊 回復
315 2
【发现】原来OPENFILENAME对话框选择文件后,会改变当前文件夹路径
一派護法 十九級
1樓 發表于:2016-1-3 23:25
例如:
【程序】
// failcreating.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <Windows.h>

#define MAX_LOADSTRING 1024

using namespace std;

void displayDirectory()
{
    TCHAR szDirectory[MAX_LOADSTRING];
    GetCurrentDirectory(MAX_LOADSTRING, szDirectory);

    cout << "当前工作目录: " << endl;
    wcout << szDirectory << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    displayDirectory();
    OPENFILENAME ofn;
    TCHAR szFile[1024] = {0};
    ZeroMemory(&ofn, sizeof(OPENFILENAME));
    ofn.lStructSize = sizeof(OPENFILENAME);
    ofn.hwndOwner = NULL;
    ofn.lpstrFile = szFile;
    ofn.nMaxFile = sizeof(szFile);
    ofn.lpstrFilter = TEXT("图像文件\0*.png;*.jpg;*.gif;*.bmp\0所有文件\0*.*\0");
    ofn.nFilterIndex = 1;
    ofn.lpstrFileTitle = NULL;
    ofn.nMaxFileTitle = 0;
    ofn.lpstrInitialDir = NULL;
    ofn.lpstrTitle = TEXT("选择怪物图像");
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
    if (GetOpenFileName(&ofn))
    {
        cout << "您选择了文件: ";
        wcout << szFile;
    }
    else
        cout << "您没有选择文件" << endl;
    displayDirectory();

    system("pause");
    return 0;
}

【运行】
当前工作目录:
E:\Users\Octopus\Documents\Visual Studio 2012\Projects\failcreating\failcreating
您选择了文件: E:\Users\Octopus\Pictures\Downloaded\adaf2edda3cc7cd9441fa8e43e012
13fb80e91d9.jpg
当前工作目录:
E:\Users\Octopus\Pictures\Downloaded
Press any key to continue . . .
一派護法 十九級
2樓 發表于:2016-1-3 23:27
这样会导致一个严重的问题:当选择了文件后,如果创建文件时文件名是相对路径的话,那么保存的文件就会在选择的文件夹目录里,而不是当前程序运行所在文件夹里。
一派護法 十九級
3樓 發表于:2016-1-3 23:29
【参考资料】
http://blog.csdn.net/qiuchangyong/article/details/8164668

使用OFN_NOCHANGEDIR即可解决问题。

回復帖子

內容:
用戶名: 您目前是匿名發表
驗證碼:
(快捷鍵:Ctrl+Enter)
 

本帖信息

點擊數:315 回複數:2
評論數: ?
作者: 巨大八爪鱼
最後回復:巨大八爪鱼
最後回復時間:2016-1-3 23:29
 
©2010-2024 Arslanbar Ver2.0
除非另有聲明,本站採用創用CC姓名標示-相同方式分享 3.0 Unported許可協議進行許可。