OpenFileDialog 类在 c++ 中无法正常工作

OpenFileDialog class not working properly in c++

本文关键字:常工作 工作 类在 c++ OpenFileDialog      更新时间:2023-10-16

我想显示由OpenFileDialog打开的文件名,但它将错误的文本发送到标题栏中。我更改了项目的字符集,但没有帮助。这是我的代码:

打开文件对话框 .h :

    class OpenFileDialog  
    {
    public:
        OpenFileDialog(){};
        void CreateOpenFileDialog(HWND hWnd, LPCWSTR Title, LPCWSTR InitialDirectory, LPCWSTR Filter, int FilterIndex);
        ~OpenFileDialog(){};
        LPCWSTR result=L"";
    };

打开文件对话框 .cpp :

      void OpenFileDialog::CreateOpenFileDialog(HWND hWnd, LPCWSTR Title, LPCWSTR InitialDirectory, LPCWSTR Filter, int FilterIndex)
       {
    OPENFILENAME ofn;
    TCHAR szFile[MAX_PATH];
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.lpstrFile = szFile;
    ofn.lpstrFile[0] = '';
    ofn.hwndOwner = hWnd;
    ofn.nMaxFile = sizeof(szFile);
    ofn.lpstrFilter = Filter;
    ofn.nFilterIndex = FilterIndex;
    ofn.lpstrTitle = Title;
    ofn.lpstrInitialDir = InitialDirectory;
    ofn.lpstrFileTitle = NULL;
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

    if (GetOpenFileName(&ofn))
    {
         result = ofn.lpstrFile;
    }
    else
    {
        result = L"Empty";
    }
}

并在 Windows 程序中WM_COMMAND:

        case WM_COMMAND:
        {
            if (LOWORD(wParam) == ID_FILE_OPEN)
            {
                OpenFileDialog ofd;
                ofd.CreateOpenFileDialog(hwnd, L"Test", L"C:\", L"All files(*.*)*.*TextFiles(*.txt)*.txt", 2);
                SetWindowText(hwnd, ofd.result);
            }
            break;
        }

多谢。

在你的函数CreateOpenFileDialog()中,用于存储文件名的缓冲区是一个本地数组szFile[MAX_PATH]。 初始化ofn结构中的lpstrFile = szFile,确保GetOpenFileName()将用户输入的结果放在正确的位置。

问题是,一旦你从 CreateOpenFileDialog() 返回,它的局部变量就会被销毁,包括包含文件名的缓冲区。因此,您使用 result = ofn.lpstrFile; 设置的result指针随后指向无效的内存位置。

可以通过在 OpenFileDialog 构造函数中直接在 result 中分配缓冲区(或使其成为数组)并直接将此指针与 ofn.lpstrFile = buffer;