首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 檔案控制項應用實例:檔名瀏覽查找系統與 FindFirst/FindNext 實作

     編輯:Delphi

系統功能與元件配置

展示檔名、選取寫入列表框、依編輯框萬用字元查找。核心元件:

元件關鍵屬性/連結
FileEditTabOrder=0,顯示當前檔案/輸入比對字串
FileListBox1FileEdit=FileEdit,顯示目錄檔案
DirectoryListBox1DirLabel=DirLabel, FileList=FileListBox1
DriveComboBox1DirList=DirectoryListBox1
FilterComboBox1FileList=FileListBox1, Filter=預設/原始碼/表單/專案
ListBox1顯示選取/搜尋結果
Button1Caption='查找',觸發搜尋
Button2Caption='退出'

元件間連結屬性設定即可實現聯動,無需代碼。

功能實作細節

選取檔案加入列表

procedure TFileCtrForm.FileListBox1Click(Sender: TObject);
begin
  if Searched then begin Searched := False; ListBox1.Items.Clear; Label5.Caption := 'Selected Files'; end;
  if NotInList(ExtractFileName(FileListBox1.FileName), ListBox1.Items) then
    ListBox1.Items.Add(ExtractFileName(FileListBox1.FileName));
end;

function TFileCtrForm.NotInList(FileName: String; Items: TStrings): Boolean;
var i: Integer;
begin
  for i := 0 to Items.Count-1 do
    if Items[i] = FileName then begin Result := False; Exit; end;
  Result := True;
end;

Searched 全域旗標區分「選取」與「搜尋」模式。

編輯框輸入萬用字元即時過濾

procedure TFileCtrForm.FileEditKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #13 then begin FileListBox1.ApplyFilePath(FileEdit.Text); Key := #0; end;
end;

ApplyFilePath 為關鍵方法。

FindFirst/FindNext 手動搜尋

procedure TFileCtrForm.Button1Click(Sender: TObject);
var i: Integer; SearchRec: TSearchRec;
begin
  Searched := True; Label5.Caption := 'Search Result'; ListBox1.Items.Clear;
  FindFirst(FileEdit.Text, faAnyFile, SearchRec);
  ListBox1.Items.Add(SearchRec.Name);
  repeat
    i := FindNext(SearchRec);
    if i = 0 then ListBox1.Items.Add(SearchRec.Name);
  until i <> 0;
end;

TSearchRec 結構與實用衍生函數

TSearchRec = record
  Fill: array[1..21] of Byte;
  Attr: Byte;      // 屬性位元
  Time: Longint;   // 時間戳
  Size: Longint;   // 檔案大小
  Name: string[12]; // 檔名
end;

衍生工具函數:

  • GetFileSize:FindFirst 成功回傳 SearchRec.Size
  • GetFileTime:回傳 SearchRec.Time(等同 FileAge)
  • 屬性檢測:(SearchRec.Attr and GivenAttr) > 0

屬性常數:faReadOnly=$01/faHidden=$02/faSysFile=$04/faVolumeID=$08/faDirectory=$10/faArchive=$20/faAnyFile=$3F。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved