Janycz
Janycz

Reputation: 155

C++ WinAPI error when GetOpenFileName

Good day. I made a class to work 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;
}

Calling:

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

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

But the program crushes on hDialog.Show(), but rather a call GetOpenFileName(&m_ofn):Unhandled exception at 0x000007FDFC5D21A3 (SHCore.dll) in ScoEditor.exe: 0xC0000005: Access violation reading location 0x000000E600000000.

How can I fix it?

Upvotes: 1

Views: 1396

Answers (1)

Raymond Chen
Raymond Chen

Reputation: 45173

Your constructor does m_ofn.lpstrFilter = Filter;, but Filter has not yet been initialized. Later, your code modifies Filter, but fails to update the value inside m_ofn.lpstrFilter. As a result, you are passing an uninitialized lpstrFilter to GetOpenFileName.

You would have discovered this if you debugged your code by setting a breakpoint on the call to GetOpenFileName and looking at the contents of the m_ofn you are passing.

Upvotes: 3

Related Questions