2012-03-02 89 views
4

可能重複:
Delphi: Selecting a directory with TOpenDialogDELPHI - 如何使用opendialog1選擇文件夾?

我需要打開我的項目的特定文件夾。當我使用opendialog1時,我只能打開一個文件。如何打開文件夾?

wanted - open folder dialog in Delphi

PS:我使用德爾福2010年

+3

肯的回答(唯一一個至今)是偉大的,但是這似乎是一個DUP:http://stackoverflow.com/questions/ 7422689/delphi-selecting-a-directory-with-topendialog – Argalatyr 2012-03-02 06:19:45

+0

事實上,你可以使用'TOpenDialog'後裔 - 'TSaveDialog'(是的,這相當快速和骯髒) – OnTheFly 2012-03-02 07:14:56

+1

投票結束,但我會失蹤['teran's answer'](http://stackoverflow.com/a/9529154/960757)。 – TLama 2012-03-02 10:47:09

回答

6

您還可以使用TBrowseForFolder動作類(stdActns.pas):

var 
    dir: string; 
begin 
    with TBrowseForFolder.Create(nil) do try 
    RootDir := 'C:\'; 
    if Execute then 
     dir := Folder; 
    finally 
    Free; 
    end; 
end; 

,或者使用WINAPI功能 - 直接SHBrowseForFolder(第二SelectDirectory超載使用它,而不是第一過載,其在運行時用所有控件創建自己的Delphi窗口):

var 
    dir : PChar; 
    bfi : TBrowseInfo; 
    pidl : PItemIDList; 
begin 
    ZeroMemory(@bfi, sizeof(bfi)); 
    pidl := SHBrowseForFolder(bfi); 
    if pidl <> nil then try 
    GetMem(dir, MAX_PATH + 1); 
    try 
     if SHGetPathFromIDList(pidl, dir) then begin 
     // use dir 
     end; 
    finally 
     FreeMem(dir); 
    end; 
    finally 
    CoTaskMemFree(pidl); 
    end; 
end; 
+0

第13,14行可以替換爲'CoTaskMemFree' – OnTheFly 2012-03-02 07:15:25

9

你在FileCtrl單位找SelectDirectory。它有兩個重載版本:

function SelectDirectory(var Directory: string; 
    Options: TSelectDirOpts; HelpCtx: Longint): Boolean; 
function SelectDirectory(const Caption: string; const Root: WideString; 
var Directory: string; Options: TSelectDirExtOpts; Parent: TWinControl): Boolean; 

您要使用的一個取決於德爾福的版本你使用,具體的外觀和功能,您正在尋找;我(通常會發現第二個版本完全適用於德爾福和Windows的現代版本,並且用戶似乎高興的「正常預期外觀和功能」

+2

+1肯,順便說一句,單位名稱是'FileCtrl'。 – RRUZ 2012-03-02 05:08:28

+1

很久以前,兩個函數都被移出了'FileCtrl'單元。 – 2012-03-02 06:40:01

+0

羅德里戈,感謝您的更正。固定。 @Remy,[XE2文檔](http://docwiki.embarcadero.com/VCL/en/FileCtrl.SelectDirectory)說你錯了。如果他們「很久以前」被移動了,文檔應該提及這個事實。 – 2012-03-02 19:23:16

13

在Vista及更高版本中,您可以使用TFileOpenDialog顯示更現代的對話框。

var 
    OpenDialog: TFileOpenDialog; 
    SelectedFolder: string; 
..... 
OpenDialog := TFileOpenDialog.Create(MainForm); 
try 
    OpenDialog.Options := OpenDialog.Options + [fdoPickFolders]; 
    if not OpenDialog.Execute then 
    Abort; 
    SelectedFolder := OpenDialog.FileName; 
finally 
    OpenDialog.Free; 
end; 

,看起來像這樣:

enter image description here