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

时间:2014-11-20 19:52:48

标签: c++ openfiledialog

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

OpenFileDialog .h:

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

OpenFileDialog .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] = '\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";
    }
}

和WM_COMMAND中的Windows过程:

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

非常感谢。

1 个答案:

答案 0 :(得分:1)

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

问题在于,只要从CreateOpenFileDialog()返回,就会销毁其局部变量,包括包含文件名的缓冲区。因此,您使用result设置的result = ofn.lpstrFile;指针指向无效的内存位置。

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

一起使用来解决此问题。