uwatcherthread.pas

来自「系统文件监控」· PAS 代码 · 共 89 行

PAS
89
字号
unit uWatcherThread;

interface
uses Classes, Windows, Dialogs,
     uWatcherInterface;

type
  TWatcherThread = class(TThread)
  private
    ChangeHandle: THandle;
    WatchPath: string;
    Owner: TComponent;
    WatchTo: TWatchTo;
  protected
    procedure Execute; override;
    procedure ChangeNotifyEvent;
    destructor Destroy; override;
  public
    constructor Create(aOwner: TComponent; aPath: string; aWatchTo: TWatchTo);
  end;

implementation  uses DirWatcher,SysUtils;

{ Important: Methods and properties of objects in VCL can only be used in a
  method called using Synchronize, for example,

      Synchronize(UpdateCaption);

  and UpdateCaption could look like,

    procedure TWatcherThread.UpdateCaption;
    begin
      Form1.Caption := 'Updated in a thread';
    end; }

{ TWatcherThread }

constructor TWatcherThread.Create(aOwner: TComponent;aPath: string;aWatchTo: TWatchTo);
begin
  inherited Create(false);  // false says that the thread will be started immediately
                            // after it is created (true means suspend-mode)
  Owner := aOwner;
  WatchPath := aPath;
  WatchTo := aWatchTo;
  FreeOnTerminate := true;
end;

procedure TWatcherThread.Execute;
var hNotifyFilter: word;
begin
  hNotifyFilter := 0;
  case WatchTo of
    wtFilenameChange:   hNotifyFilter := FILE_NOTIFY_CHANGE_FILE_NAME;
    wtDirNameChange:    hNotifyFilter := FILE_NOTIFY_CHANGE_DIR_NAME;
    wtAttributesChange: hNotifyFilter := FILE_NOTIFY_CHANGE_ATTRIBUTES;
    wtFilesizeChange:   hNotifyFilter := FILE_NOTIFY_CHANGE_SIZE;
    wtLastwriteChange:  hNotifyFilter := FILE_NOTIFY_CHANGE_LAST_WRITE;
    wtSecurityChange:   hNotifyFilter := FILE_NOTIFY_CHANGE_SECURITY;
  end; // case

  ChangeHandle:= FindFirstChangeNotification(PChar(WatchPath), false, hNotifyFilter);

  if ChangeHandle <> INVALID_HANDLE_VALUE then
    while true do
    begin
      if WaitForSingleObject(ChangeHandle,500{or INFINITE}) = WAIT_OBJECT_0 then
      begin
        Synchronize(ChangeNotifyEvent);
      end;
      FindNextChangeNotification(ChangeHandle);
      if Terminated then
        Break;
    end;
end;

procedure TWatcherThread.ChangeNotifyEvent;
begin
  TDirWatcher(Owner).NotifyEvent;
end;

destructor TWatcherThread.Destroy;
begin
  if ChangeHandle <> NULL then FindCloseChangeNotification(ChangeHandle);
  inherited Destroy;
end;


end.

⌨️ 快捷键说明

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