Using GetOpenFileName
I made a stupid mistake today.
I need to get a file path, so I use GetOpenFileName .Following is the definition:
BOOL GetOpenFileName( LPOPENFILENAME lpofn);
According to the description in MSDN,I just need to fill the OPENFILENAME structure.And here is my code:
char szFilePath[MAX_PATH];
OPENFILENAME stOpenFileName;
BOOL zRet;
RtlZeroMemory(&stOpenFileName ,sizeof(OPENFILENAME));
stOpenFileName.lStructSize = sizeof(OPENFILENAME);
stOpenFileName.lpstrFilter = “驱动(*.sys)\0\0″;
stOpenFileName.lpstrFile = szFilePath;
stOpenFileName.nMaxFile = MAX_PATH;
stOpenFileName.Flags = OFN_FILEMUSTEXIST;
zRet = GetOpenFileName(&stOpenFileName);
The code above can run successfully,but it never shows the file-choosen dialog.
Then I search for the usage of GetOpenFileName,But I got nothing.
After about an hour ,I ran the program and get the dialog with messy code. So I rechecked my code and read MSDN’s
description about OPENFILENAME .And I found that :
- lpstrFilter
- Long pointer to a buffer that contains pairs of null-terminated filter strings. The last string in the buffer must be terminated by two NULL characters.
Finally,I descovered that I’ve forgot to initialize szFilePath .After I add :
RtlZeroMemory(szFilePath ,sizeof(char)*MAX_PATH);
The dialog appeared.
Following is the correct code:
int main()
{
char szFilePath[MAX_PATH];
OPENFILENAME stOpenFileName;
BOOL zRet;
RtlZeroMemory(&stOpenFileName ,sizeof(OPENFILENAME));
RtlZeroMemory(szFilePath ,sizeof(char)*MAX_PATH);
stOpenFileName.lStructSize = sizeof(OPENFILENAME);;
stOpenFileName.lpstrFilter = “驱动(*.sys)\0\0″;
stOpenFileName.lpstrFile = szFilePath;
stOpenFileName.nMaxFile = MAX_PATH;
stOpenFileName.Flags = OFN_FILEMUSTEXIST;
zRet = GetOpenFileName(&stOpenFileName);
MessageBox(NULL ,stOpenFileName.lpstrFile ,NULL ,0);
return 0;
}

发表评论