要求:利用Win32 API SHBrowseForFolder开启一个选择文件目录的对话框,预先定位到默认的目录,最后返回所选择的结果
代码如下:
function BrowseCallbackProc(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer stdcall;
begin
case uMsg of
BFFM_INITIALIZED: SendMessage(Wnd, BFFM_SETSELECTION, 1, lpData);
end;
Result := 0;
end;
function BrowsFolder(const Folder: string): string;
var
TitleName: string;
lpItemID: PItemIDList;
BrowseInfo: TBrowseInfo;
DisplayName: array[0..MAX_PATH] of char;
TempPath: array[0..MAX_PATH] of char;
begin
Result := Folder;
FillChar(BrowseInfo, sizeof(TBrowseInfo), #0);
BrowseInfo.hwndOwner := GetActiveWindow;
BrowseInfo.pszDisplayName := @DisplayName;
TitleName := ''Please specify a directory'';
BrowseInfo.lpszTitle := PChar(TitleName);
BrowseInfo.ulFlags := BIF_RETURNONLYFSDIRS;
BrowseInfo.lpfn := BrowseCallbackProc;
BrowseInfo.lParam := Integer(PChar(Folder));
lpItemID := SHBrowseForFolder(BrowseInfo);
if Assigned(lpItemId) then begin
SHGetPathFromIDList(lpItemID, TempPath);
GlobalFreePtr(lpItemID);
Result := string(TempPath);
end;
end;
函数BrowsFolder是主体,传入参数即默认的目录,返回值即选择的结果.BrowseCallbackProc是由SHBrowseForFolder执行时需要的回调(Call Back)函数,在这个函数中,截取了BFFM_INITIALIZED消
息,在目录选择对话框初始化的时候,向对话框发送一个BFFM_SETSELECTION消息,选中默认的目录.