美好的一天。我制作了一个类来使用OpenFileDialog:

#include <Windows.h>

enum DialogResult { OK, Cancel };

class IFileDialog
{
public:
    TCHAR FileName[MAX_PATH];
    LPTSTR Title;
    virtual DialogResult Show() = 0;
};

class COpenFileDialog  : public IFileDialog
{
public:
    LPTSTR Filter;
    LPTSTR DefExt;
    COpenFileDialog(HWND hWnd);
    DialogResult Show();
private:
    OPENFILENAME m_ofn;
};

COpenFileDialog::COpenFileDialog(HWND hWnd)
{
    //FileName[0] = '\0';

    ZeroMemory(&m_ofn, sizeof(m_ofn));

    m_ofn.lStructSize = sizeof(m_ofn);
    m_ofn.hwndOwner = hWnd;
    m_ofn.lpstrFilter = Filter;
    m_ofn.nMaxFile = MAX_PATH;
    m_ofn.lpstrFile = FileName;
    m_ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
    m_ofn.lpstrDefExt = DefExt;
}

DialogResult COpenFileDialog::Show()
{
    return GetOpenFileName(&m_ofn) ? DialogResult::OK : DialogResult::Cancel;
}

致电:
COpenFileDialog hDialog = COpenFileDialog(hMainWindow);
hDialog.Filter = "M&B Scenes\0*.sco\0";
hDialog.DefExt = "sco";
hDialog.Title = "";

if(hDialog.Show() == DialogResult::OK)
{
    //TODO
}

但是程序在hDialog.Show()上崩溃,而是在ScoEditor.exe中的0x000007FDFC5D21A3(SHCore.dll)处调用GetOpenFileName(&m_ofn):未处理的异常:0xC0000005:访问冲突读取位置0x000000E600000000。

我该如何解决?

最佳答案

您的构造函数执行m_ofn.lpstrFilter = Filter;,但是Filter尚未初始化。稍后,您的代码将修改Filter,但是无法更新m_ofn.lpstrFilter内部的值。结果,您正在将未初始化的lpstrFilter传递给GetOpenFileName

如果通过在对GetOpenFileName的调用上设置一个断点并查看所传递的m_ofn的内容来调试代码,您将发现这一点。

09-05 13:15