moonman239 moonman239 - 1 year ago 102
C++ Question

GetOpenFileNameA causes common dialog error 2

I'm trying to open a dialog box using GetOpenFileNameA. However, the dialog does not open. Instead, I get a nice CommDlgError 2. Searching Google and StackOverflow for this error did not produce any helpful results.

Note: All variables not declared in this block of code are "global" variables that are only accessible within the main code module.

void GetInputFile()
char szFileNameIN[MAX_PATH];
char szFileNameOUT[MAX_PATH];

// get the input file name
ZeroMemory(&fInputPath, sizeof(fInputPath));
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = LPWSTR("Any File\0*.*\0");
ofn.lpstrFile = LPWSTR(fInputPath);
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFileTitle = LPWSTR(szFileNameIN);
ofn.nMaxFileTitle = MAX_PATH;
ofn.lpstrTitle = LPWSTR("Select an input File");
if (GetOpenFileNameA(LPOPENFILENAMEA(&ofn))) // user selected an input file
else {
// Get error


Answer Source

Those awful (LPWSTR) casts tell me that you are compiling with _UNICODE defined, so the OPENFILENAME struct you are using is actually OPENFILENAMEW; given that you are using GetOpenFileNameA, you have to use OPENFILENAMEA (or use straight GetOpenFileName with wide strings).

(and remember that, as a rule of thumb, if you have to cast pointers to/from anything different than void * and similar, you are probably doing something wrong; adding pointer casts will only silence the compiler, not make the error go away)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download