Delphi 打开文件夹方法

第一种方法,使用SelectDirectory 函数 ,在ShellApi中

procedure TForm2.BtSelectPathClick(Sender: TObject);
var
    strCaption,strDirectory:String;
    wstrRoot:WideString;
    begin
    strCaption:='这是浏览文件夹的说明文字,可以根据需要进行书写。'
    +#13#10+'一般二行文字就满了。';
    //该参数是浏览文件夹窗口的显示说明部分
    wstrRoot:='';
    //这个参数表示所显示的浏览文件夹窗口中的根目录,默认或空表示“我的电脑”。
    SelectDirectory(strCaption,wstrRoot,strDirectory);
    EdLocalPath.Text:=strDirectory;
end;

第二种方法

要求:利用Win32 API SHBrowseForFolder开启一个选择文件目录的对话框,预先定位到默认的目录,最后返回所选择的结果,如果没有进行选择(即单击“取消”结束选择)则返回空''。

代码如下:(以下两个函数定义需要在uses中引入两个单元ShlObj,Windows;)

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 := '请选择一个目录';
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
else
    Result:='';
end;

      函数BrowsFolder是主体,传入参数即默认的目录,返回值即选择的结果。

     BrowseCallbackProc是由SHBrowseForFolder执行时需要的回调(Call Back)函数。在这个函数中,截取了BFFM_INITIALIZED消息,在目录选择对话框初始化的时候,向对话框发送一个BFFM_SETSELECTION消息,选中默认的目录。

原文地址:https://www.cnblogs.com/iapp/p/3631880.html