TomJeffries
TomJeffries

Reputation: 568

Problems with GetOpenFileName()

I'm having problems with the following code:

HANDLE hFile;
DWORD bytesRead;
OPENFILENAME ofn;
DWORD problem;
WCHAR title[260];

ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = hWnd;
ofn.lpstrFile = (LPWSTR)title;
ofn.nMaxFile = sizeof(title);
ofn.lpstrFilter = TEXT("All files(*.*)\0*.*\0");
ofn.nFilterIndex = 1;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

if (GetOpenFileName(&ofn) == false)
{
    problem = CommDlgExtendedError();
    return false;
}

From GetOpenFileName it simply goes to problem = CommDlgExtendedError(); without putting up a dialog.

Upvotes: 0

Views: 1435

Answers (1)

Ari0nhh
Ari0nhh

Reputation: 5930

You have to allocate a memory for the lpstrFile struct member and set nMaxFile to its size. Also first character of the buffer should be set to \0 to prevent file name initialization. MSDN example:

// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not 
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';

Upvotes: 4

Related Questions