CnCommon单元之GetDirectory、FormatPath【5】
function SelectDirCB(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer stdcall; begin if (uMsg = BFFM_INITIALIZED) and (lpData <> 0) then SendMessage(Wnd, BFFM_SETSELECTION, Integer(True), lpdata); Result := 0; end; function CnSelectDirectory(const Caption: string; const Root: WideString; var Directory: string; Owner: HWND; ShowNewButton: Boolean = True): Boolean; var BrowseInfo: TBrowseInfo; Buffer: PChar; RootItemIDList, ItemIDList: PItemIDList; ShellMalloc: IMalloc; IDesktopFolder: IShellFolder; Eaten, Flags: LongWord; begin Result := False; FillChar(BrowseInfo, SizeOf(BrowseInfo), 0); if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then begin Buffer := ShellMalloc.Alloc(MAX_PATH); try SHGetDesktopFolder(IDesktopFolder); if Root = '' then RootItemIDList := nil else IDesktopFolder.ParseDisplayName(Application.Handle, nil, POleStr(Root), Eaten, RootItemIDList, Flags); with BrowseInfo do begin hwndOwner := Owner; pidlRoot := RootItemIDList; pszDisplayName := Buffer; lpszTitle := PChar(Caption); ulFlags := BIF_RETURNONLYFSDIRS; if ShowNewButton then ulFlags := ulFlags or $0040; lpfn := SelectDirCB; lparam := Integer(PChar(Directory)); end; ItemIDList := SHBrowseForFolder(BrowseInfo); Result := ItemIDList <> nil; if Result then begin ShGetPathFromIDList(ItemIDList, Buffer); ShellMalloc.Free(ItemIDList); Directory := Buffer; end; finally ShellMalloc.Free(Buffer); end; end; end; //显示选择文件夹对话框,支持设置默认文件夹 function GetDirectory(const Caption: string; var Dir: string; ShowNewButton: Boolean=True): Boolean; var OldErrorMode: UINT; BrowseRoot: WideString; OwnerHandle: HWND; begin OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try BrowseRoot := ''; if Screen.ActiveCustomForm <> nil then OwnerHandle := Screen.ActiveCustomForm.Handle else OwnerHandle := Application.Handle; Result := CnSelectDirectory(Caption, BrowseRoot, Dir, OwnerHandle, ShowNewButton); finally SetErrorMode(OldErrorMode); end; end; uses ShlObj, ActiveX
有时候不想选择文件,只想选择文件夹,这个函数排上用场.
// 缩短显示不下的长路径名 function FormatPath(const APath: string; Width: Integer): string; var SLen: Integer; i, j: Integer; TString: string; begin SLen := Length(APath); if (SLen <= Width) or (Width <= 6) then begin Result := APath; Exit end else begin i := SLen; TString := APath; for j := 1 to 2 do begin while (TString[i] <> '\') and (SLen - i < Width - 8) do i := i - 1; i := i - 1; end; for j := SLen - i - 1 downto 0 do TString[Width - j] := TString[SLen - j]; for j := SLen - i to SLen - i + 2 do TString[Width - j] := '.'; Delete(TString, Width + 1, 255); Result := TString; end; end;
这个函数我真的很少会用到,记得好多年前用过一次.有的路劲太长了,不方便看,用此函数做缩减
如果觉得文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
作者:YXGust
出处:https://www.cnblogs.com/YXGust/p/14749364.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
本博文版权归本博主所有,转载请注明原文链接
微信打赏
支付宝打赏
浙公网安备 33010602011771号