测试例程
#include <stdio.h>
#include <string.h>
#include <windows.h>
int main(int argc, char** argv)
{
int r;
char retpath[MAX_PATH+1];
OPENFILENAME ofn ;
memset(&ofn, 0, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrDefExt = NULL;
ofn.lpstrFile = retpath;
if(argc>=2)
strncpy(retpath, argv[1], strlen(argv[1])<MAX_PATH?strlen(argv[1]):MAX_PATH);
else
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFilter = NULL;
ofn.nFilterIndex = 0;
ofn.lpstrInitialDir = NULL;
ofn.lpstrTitle = "Test";
ofn.Flags = 0;
r=GetOpenFileName(&ofn);
if(r)
printf("GetOpenFileName got filename %s", retpath);
else
printf("error: %d", GetLastError());
return 0;
}
编译:
D:\>c:\mingw2\bin\gcc gofn.c -lcomdlg32 -ogofn.exe
运行第一次(不输入命令行参数),弹出对话框输入
https://www.v2ex.com 后,对话框卡了一下后返回
D:\>gofn
GetOpenFileName got filename C:\Users\user\AppData\Local\Microsoft\Windows\INetCache\IE\TJ1BE227\3OQBB5YK
运行第二次,命令行输入
D:\>gofn c:\windows\win.ini
GetOpenFileName got filename C:\Windows\win.ini
对话框正常弹出并自动定位到正确的目录。
运行第三次,命令行输入
D:\>gofn
https://www.v2ex.comerror: 0
对话框不弹出且 GetLastError 不能得到错误码。这就不知道为什么了。