![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
unit FileSysThread;
interface
uses
Windows, SysUtils, Classes, comctrls;
type
TFileSysNotifyThread = class(TThread)
private
ErrCode: Integer;
KillAddress: PInteger;
NotifyHandle: THandle;
WatchPath: string;
WatchMask: Integer;
procedure SignalFileNotification;
protected
procedure Execute; override;
public
constructor Create(const AWatchPath: string; AWatchMask: Integer; var
Myself: TFileSysNotifyThread);
destructor Destroy; override;
end;
implementation
uses Dialogs;
constructor TFileSysNotifyThread.Create(const AWatchPath: string; AWatchMask:
Integer; var Myself: TFileSysNotifyThread);
begin
inherited Create(True);
WatchPath := AWatchPath;
WatchMask := AWatchMask;
KillAddress := Addr(Myself);
Priority := tpLower;
FreeOnTerminate := True;
Suspended := False;
end;
destructor TFileSysNotifyThread.Destroy;
begin
if NotifyHandle <> THandle(-1) then
FindCloseChangeNotification(NotifyHandle);
inherited Destroy;
KillAddress^ := 0;
end;
procedure TFileSysNotifyThread.Execute;
begin
NotifyHandle := FindFirstChangeNotification(PChar(WatchPath), False,
WatchMask);
if NotifyHandle <> THandle(-1) then
while not Terminated do
begin
ErrCode := WaitForSingleObject(NotifyHandle, 250);
case ErrCode of
Wait_Timeout:
;
Wait_Object_0:
begin
Synchronize(SignalFileNotification);
FindNextChangeNotification(NotifyHandle);
end;
else
;
end;
end;
end;
procedure TFileSysNotifyThread.SignalFileNotification;
begin
ShowMessage('文件已改变!');
end;
end.
unit Test;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, ExtCtrls, FileSysThread;
type
TForm1 = class(TForm)
Button1: TButton;
Button3: TButton;
Edit1: TEdit;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
MyThread1: TFileSysNotifyThread;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
if MyThread1 = nil then
MyThread1 := TFileSysNotifyThread.Create(edit1.text,
File_Notify_Change_File_Name or File_Notify_Change_Dir_Name, MyThread1)
else
ShowMessage('线程正在运行');
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
if MyThread1 <> nil then
MyThread1.Terminate
else
ShowMessage('线程未运行');
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
if MyThread1 <> nil then
begin
MyThread1.Terminate;
MyThread1.WaitFor;
end;
end;
end.