Re: GetOpenFileName causes lock-up
rik ha scritto:
Hi,
having a problem where using GetOpenFileName crashes in debug mode
only.
To test it I grabbed an example off CodeGuru and found that if I
modify the filter it will cause my program to lockup
ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0";
<< this works!!
but
ofn.lpstrFilter = "Text Files (*.txt)\0*.txi\0All Files (*.*)\0*.*\0";
<< Lock-up
Could you please give us more details about "crash"?
What precise error message do you get?
The only difference I can spot between the above two filter strings is
the (wrong) extension "txi" instead of "txt" in the second filter string.
or
ofn.lpstrFilter = ""; << Lock-up
or
ofn.lpstrFilter = "\0\0"; << Lock-up
What's up?
I tried the following code on VS2008 and Vista, and it works fine in all
the three cases that you marked as "Lock-up":
<code>
//////////////////////////////////////////////////////////////////////////
// Test.cpp
#define WIN32_LEAN_AND_MEAN
#define STRICT
#include <tchar.h>
#include <windows.h>
#include <CommDlg.h>
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
OPENFILENAME ofn;
TCHAR szFileName[MAX_PATH] = _T("");
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = _T("Text Files (*.txt)\0*.txi\0All Files
(*.*)\0*.*\0"); // case #1
// ofn.lpstrFilter = _T(""); // case #2
// ofn.lpstrFilter = _T("\0\0"); // case #3
ofn.lpstrFile = szFileName;
ofn.nMaxFile = MAX_PATH;
if(GetOpenFileName(&ofn))
{
// Do something useful with the filename stored in szFileName
MessageBox(NULL, szFileName, _T("Filename:"), MB_OK);
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
</code>
// ------------ code segment ------------------
OPENFILENAME ofn;
char szFileName[MAX_PATH] = "";
I would suggest you to use a TCHAR here, and _T() decorator for "" empty
string.
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = "Text Files (*.txt)\0*.txi\0All Files (*.*)\0*.*\0";
Again, you may want to decorate the above string with _T() to make your
code Unicode aware.
Moreover, I'm not sure if better practice would be to use a double \0 as
the terminator in the filter string, e.g. "...\0*.*\0\0".
(However, in code I tested, I put a single \0, and it seemed to work fine.)
HTH,
Giovanni