設置 | 登錄 | 註冊

作者共發了3篇帖子。

【發現】原來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即可解決問題。

內容轉換:

回覆帖子
內容:
用戶名: 您目前是匿名發表。
驗證碼:
看不清?換一張
©2010-2025 Purasbar Ver3.0 [手機版] [桌面版]
除非另有聲明,本站採用知識共享署名-相同方式共享 3.0 Unported許可協議進行許可。