【问题标题】:OpenFileDialog class not working properly in c++OpenFileDialog 类在 C++ 中无法正常工作
【发布时间】:2014-11-20 19:52:47
【问题描述】:

我想显示由 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;
        }

非常感谢。

【问题讨论】:

    标签: c++ openfiledialog


    【解决方案1】:

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

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

    您可以通过在OpenFileDialog 构造函数中直接在result 中分配缓冲区(或将其设为数组)来解决此问题,并直接将此指针与ofn.lpstrFile = buffer; 一起使用

    【讨论】:

      猜你喜欢
      • 2013-08-30
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 2020-08-01
      相关资源
      最近更新 更多