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!?!?
The documentation for
lpstrFilestates:You are not initializing
flnmand therein lies the problem. You can solve the problem by writingflnm[0] = '\0'before you callGetOpenFileName.