main.pas

来自「delphi开发语言下的源代码分析」· PAS 代码 · 共 122 行

PAS
122
字号
unit main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TWatchThread = class(TThread)
  private
    FInfo : String;
    hHandles : array of THandle;
    WatchTarget : array of String;
    procedure ShowNotifyInfo;
    procedure AddNotifyRec;
  public
    procedure Execute; override;
  end;

  TMainForm = class(TForm)
    AddBtn: TButton;
    DirectoryEdit: TEdit;
    DirectoryListBox: TListBox;
    procedure AddBtnClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    WatchThread : TWatchThread;
  public
    { Public declarations }
  end;

var
  MainForm: TMainForm;

implementation

{$R *.dfm}

procedure TWatchThread.ShowNotifyInfo;
begin
  ShowMessage(Self.FInfo);
end;

procedure TWatchThread.AddNotifyRec;
begin
  MainForm.DirectoryListBox.Items.Add(MainForm.DirectoryEdit.Text);
end;

var
  CreateNotifyEvent : THandle;

procedure TWatchThread.Execute;
var
  Id : Integer;
  WAIT_OBJECT_N : Integer;
begin
  SetLength(hHandles, 1);
  SetLength(WatchTarget, 1);
  hHandles[0] := CreateNotifyEvent;
  WatchTarget[0] := '';

  repeat
    WAIT_OBJECT_N := WaitForMultipleObjects(Length(hHandles), @hHandles[0], false, INFINITE);
    if WAIT_OBJECT_N = WAIT_FAILED then break;

    WAIT_OBJECT_N := WAIT_OBJECT_N - WAIT_OBJECT_0;
    if WAIT_OBJECT_N = 0 then
    begin
      ResetEvent(hHandles[0]);

      // 添加一个新的监视记录
      Id := Length(hHandles);
      SetLength(hHandles, Id+1);
      SetLength(WatchTarget, Id+1);
      WatchTarget[Id] := MainForm.DirectoryEdit.text;

      hHandles[Id] := FindFirstChangeNotification(PChar(WatchTarget[Id]), true,
        FILE_NOTIFY_CHANGE_FILE_NAME or
        FILE_NOTIFY_CHANGE_DIR_NAME or 
        FILE_NOTIFY_CHANGE_LAST_WRITE);
      if hHandles[Id] <> INVALID_HANDLE_VALUE then
        Synchronize(AddNotifyRec)
      else
      begin
        FInfo := '监视不成功(不存在?): ' + WatchTarget[Id];
        Synchronize(ShowNotifyInfo);
        SetLength(hHandles, Id);
        SetLength(WatchTarget, Id);
      end;
    end
    else
    begin
      if WAIT_OBJECT_N >= Length(hHandles) then Continue;

      FInfo := '目录中存在修改: ' + WatchTarget[WAIT_OBJECT_N];
      Synchronize(ShowNotifyInfo);
      FindNextChangeNotification(hHandles[WAIT_OBJECT_N]);
    end;
  until Terminated;
end;


procedure TMainForm.AddBtnClick(Sender: TObject);
begin
  setEvent(CreateNotifyEvent);
end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  CreateNotifyEvent := CreateEvent(nil, True, False, '');
  WatchThread := TWatchThread.Create(false);
end;

procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  WatchThread.Terminate;
end;

end.

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?