GetOpenFileName时出现C ++ WinAPI错误

时间:2013-12-21 15:36:03

标签: c++ winapi visual-studio-2012

美好的一天。我开了一个班来上班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(),而是调用GetOpenFileName(&amp; m_ofn):ScoEditor.exe中0x000007FDFC5D21A3(SHCore.dll)的未处理异常:0xC0000005:访问冲突读取位置0x000000E600000000。

我该如何解决?

1 个答案:

答案 0 :(得分:3)

您的构造函数执行m_ofn.lpstrFilter = Filter;,但Filter尚未初始化。稍后,您的代码会修改Filter,但无法更新m_ofn.lpstrFilter中的值。因此,您将未初始化的lpstrFilter传递给GetOpenFileName

如果您通过在调用GetOpenFileName时设置断点并查看正在传递的m_ofn的内容来调试代码,则会发现这一点。