seth
seth

Reputation: 139

Very strange GetOpenFileName problem

I seem to be having a very strange problem with GetOpenFileName.

It errors for no apparent reason, however, if I call CommDlgExtendedError() in the error check, the error never happens in the first place.

Here is my code:

#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    OPENFILENAME fm;
    char flnm[MAX_PATH];
    ZeroMemory(&fm, sizeof(fm));

    fm.lStructSize = sizeof(OPENFILENAME);
    fm.hwndOwner = NULL;
    fm.lpstrFilter = "Text Files (*.txt)\0*.txt\0";
    fm.lpstrFile = flnm;
    fm.nMaxFile = MAX_PATH;
    fm.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
    fm.lpstrDefExt = "";

    if(!GetOpenFileNameA(&fm))
    {
        MessageBoxA(NULL, "failed! :(", NULL, NULL);
    }

    return 0;
}

What's shown? "failed! :("

If I remove this check, I do see a file dialog. However, it doesn't work, and the filename box is pre-filled with random junk.

If I change to:

if(!GetOpenFileNameA(&fm))
{
    DWORD dwErr = CommDlgExtendedError();
    MessageBoxA(NULL, "failed! :(", NULL, NULL);
}

"failed! :(" is NOT shown. The file dialog shows and performs without issue.

What is going on!?!?

Upvotes: 0

Views: 4965

Answers (1)

David Heffernan
David Heffernan

Reputation: 613491

OPENFILENAME fm;
char flnm[MAX_PATH]; // nobody initialized me ...
ZeroMemory(&fm, sizeof(fm));

fm.lStructSize = sizeof(OPENFILENAME);
fm.hwndOwner = NULL;
fm.lpstrFilter = "Text Files (*.txt)\0*.txt\0";
fm.lpstrFile = flnm; // ... who knows what I am?
fm.nMaxFile = MAX_PATH;
fm.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
fm.lpstrDefExt = "";

if(!GetOpenFileNameA(&fm))
{
        MessageBoxA(NULL, "failed! :(", NULL, NULL);
}

The documentation for lpstrFile states:

The file name used to initialize the File Name edit control. The first character of this buffer must be NULL if initialization is not necessary. When the GetOpenFileName or GetSaveFileName function returns successfully, this buffer contains the drive designator, path, file name, and extension of the selected file.

You are not initializing flnm and therein lies the problem. You can solve the problem by writing flnm[0] = '\0' before you call GetOpenFileName.

Upvotes: 5

Related Questions