简体   繁体   中英

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!?!?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM