求教:如何捕获磁盘上新生成/删除一个文件的消息

解决方案 »

  1.   

    在WIN32下用DELPHI侦测目录变化,可用WIN32提供的文件改变通知API来完成。FindFirstChangeNotification, FindNextChangeNotification,FindCloseChangeNotification。 
    在应用程序中调用这些函数时,产生一个监控这个变化的句柄,可用WAIT函数集来等待这个变化。这样,当监控程序运行时,可以达到监控文件变化的动作。更进一步,可把此程序做成一个状态区图标(TRAY)来完成监控。Windows在删除、复制、移动、访问文件时并不发送消息,当然截获不到。要截取这些操作过程的唯一办法就是截获API,这又需要你编写Vxd程序了,杀毒软件都是这样作的。你注意一下杀毒软件一般都带有一个vxd程序。光有vxd还不行,还需截获文件API。还有另外一个办法,就是CIH病毒采用的办法,直接跳到系统零层去操作。具体办法如下:一、SIDT指令( 将中断描述符表寄存器IDTR--64位宽,16~47Bit存有中断描述符表IDT基地址--的内容存入指定地址单元)不是特权指令,就是说我们可以在Ring3下执行该指令,获得IDT的基地址,从而修改IDT,增加一个中断门安置我们的中断服务,一旦Ring3程序中产生此中断,VMM就会调用此中断服务程序,而此中断服务程序就运行在Ring0下了。这一点与在DOS下非常相似。二、要实现对系统中所有文件I/O操作的实时监视,还要用到另一种关键技-FileHooking,通过挂接一个处理函数,截获所有与文件I/O操作有关的系 统调用。Windows9x使用32位保护模式可安装文件系统(IFS),由可安装文件系统管理器(IFSManager)协调对文件系统和设备的访问,它接收以Win32API函数调用形式向系统发出的文件I/O请求,再将请求转给文件系统驱动程序FSD,由它调用低级别的IOS系统实现最终访问。每个文件I/OAPI调用都有一个特定的FSD函数与之对应,IFSManager负责完成由API到FSD的参数装配工作,在完成文件I/OAPI函数参数的装配之后转相应FSD执行之前,它会调用一个称为FileSystemApiHookFunction的Hooker函数。通过安装自己的Hooker函数,就可以截获系统内所有对文件I/O的API调用,从而实现实时监控。=========================================procedure TForm1.Button2Click(Sender: TObject);begin{establish a notification for file name changes on the selected directory}NotificationHandle := FindFirstChangeNotification(PChar(DirectoryListBox1.Directory), FALSE,FILE_NOTIFY_CHANGE_FILE_NAME);{if the notification was set up correctly, modify some UI elements...}if (NotificationHandle <> INVALID_HANDLE_VALUE) thenbeginButton1.Enabled := TRUE;Button2.Enabled := FALSE;endelsebegin{...otherwise indicate that there was an error}ShowMessage('There was an error setting the notification');Exit;end;end;procedure TForm1.Button1Click(Sender: TObject);vardwResult: DWORD; // holds the result of waiting on the notificationWaiting: Boolean; // loop control variablebegin{setup the loop control for a continuous loop}Waiting := TRUE;{indicate that the application is waiting for the change notification to fire}Button1.Enabled := FALSE;StatusBar1.SimpleText := 'Now waiting for a filename change';Application.ProcessMessages;{enter the loop}while Waiting dobegin{at this point, the application is suspended until the notificationobject is signaled that a filename change has occured in theselected directory (this includes file deletions)}dwResult := WaitForSingleObject(NotificationHandle,INFINITE);if (dwResult = WAIT_OBJECT_0) thenbegin{indicate that the notification object was signaled}ShowMessage('The selected directory signaled a filename change');{query the user to see if they wish to continue monitoring thisdirectory}if Application.MessageBox('Do you wish to continue monitoring this directory?', 'Continue?', MB_ICONQUESTION orMB_YESNO) = IDYES then{if the user wishes to continue monitoring the directory, resetthe notification object and continue the loop...}FindNextChangeNotification(NotificationHandle)else{...otherwise break out of the loop}Waiting := FALSE;end;end;{close the notification object}
      

  2.   

    FindCloseChangeNotification(NotificationHandle);{reset UI elements}Button1.Enabled := FALSE;Button2.Enabled := TRUE;StatusBar1.SimpleText := '';FileListBox1.Update;end;===========================================下面是一个监视的控件:unit dirnotify;interfaceusesWindows, Messages, SysUtils, Classes,Graphics, Controls, Forms, Dialogs;typeEDirNotificationError = class(Exception);TDirNotify = class;TNotifyFilter = (nfFileName, nfDirName, nfAttributes, nfSize, nfLastWrite,nfSecurity);TNotifyFilters = set of TNotifyFilter;TNotificationThread = class(TThread)Owner: TDirNotify;procedure Execute; override;procedure DoChange;end;TDirNotify = class(TComponent)privateFEnabled: Boolean;FOnChange: TNotifyEvent;FNotificationThread: TNotificationThread;FPath: String;FWatchSubTree: Boolean;FFilter: TNotifyFilters;procedure SetEnabled( Value: Boolean );procedure SetOnChange( Value: TNotifyEvent );procedure SetPath( Value: String );procedure SetWatchSubTree( Value: Boolean );procedure SetFilter( Value: TNotifyFilters );procedure RecreateThread;protectedprocedure Change;procedure Loaded; override;publicconstructor Create(AOwner: TComponent); override;destructor Destroy; override;publishedproperty Enabled: Boolean read FEnabled write SetEnabled default True;property OnChange: TNotifyEvent read FOnChange write SetOnChange;property Path: String read FPath write SetPath;property WatchSubTree: Boolean read FWatchSubTree write SetWatchSubTree;property Filter: TNotifyFilters read FFilter write SetFilter default [nfFileName, nfDirName, nfAttributes, nfLastWrite, nfSecurity];end; procedure Register;implementationconstLASTERRORTEXTLENGTH = 500;varLastErrorText: array [0..LASTERRORTEXTLENGTH] of char; function GetLastErrorText: PChar;beginFormatMessage( FORMAT_MESSAGE_FROM_SYSTEM,nil, GetLastError, 0, LastErrorText, LASTERRORTEXTLENGTH, nil );Result := LastErrorText;end; procedure TNotificationThread.Execute;varh: THandle;nf: Longint;wst: LongBool;beginnf := 0;if (nfFileName in Owner.Filter) then nf := FILE_NOTIFY_CHANGE_FILE_NAME;if (nfDirName in Owner.Filter) then nf := nf or FILE_NOTIFY_CHANGE_DIR_NAME;if (nfAttributes in Owner.Filter) then nf := nf or FILE_NOTIFY_CHANGE_ATTRIBUTES;if (nfSize in Owner.Filter) then nf := nf or FILE_NOTIFY_CHANGE_SIZE;if (nfLastWrite in Owner.Filter) then nf := nf or FILE_NOTIFY_CHANGE_LAST_WRITE;if (nfSecurity in Owner.Filter) then nf := nf or FILE_NOTIFY_CHANGE_SECURITY;// yeahh, this one is stupid but Win98 malfunctions in any other value than 0 or 1if Owner.FWatchSubTree then wst := Longbool(1)else wst := Longbool(0);h := FindFirstChangeNotification( Pointer(Owner.Path), wst, nf );if (h = INVALID_HANDLE_VALUE) thenraise EDirNotificationError.Create( GetLastErrorText );repeatif (WaitForSingleObject( h, 1000 ) = WAIT_OBJECT_0) thenbeginSynchronize(DoChange);if not FindNextChangeNotification( h ) thenraise EDirNotificationError.Create( GetLastErrorText );end;until Terminated;end;
      

  3.   

    procedure TNotificationThread.DoChange;beginOwner.Change;end; constructor TDirNotify.Create(AOwner: TComponent);begininherited Create(AOwner);FEnabled := True;FFilter := [nfFileName];end; destructor TDirNotify.Destroy;beginFNotificationThread.Free;inherited Destroy;end;procedure TDirNotify.Loaded;begininherited;RecreateThread;end; procedure TDirNotify.SetEnabled(Value: Boolean);beginif Value <> FEnabled thenbeginFEnabled := Value;RecreateThread;end;end; procedure TDirNotify.SetPath( Value: String );beginif Value <> FPath thenbeginFPath := Value;RecreateThread;end;end; procedure TDirNotify.SetWatchSubTree( Value: Boolean );beginif Value <> FWatchSubTree thenbeginFWatchSubTree := Value;RecreateThread;end;end; procedure TDirNotify.SetFilter( Value: TNotifyFilters );beginif Value <> FFilter thenbeginFFilter := Value;RecreateThread;end;end; procedure TDirNotify.SetOnChange(Value: TNotifyEvent);beginFOnChange := Value;end; procedure TDirNotify.Change;beginif Assigned(FOnChange) thenFOnChange(Self);end; procedure TDirNotify.RecreateThread;begin// destroy threadFNotificationThread.Free;FNotificationThread := nil;if FEnabled and not(csDesigning in ComponentState)and not(csLoading in ComponentState) and (FPath <> '') thenbegin// create threadFNotificationThread := TNotificationThread.Create(True);FNotificationThread.Owner := self;FNotificationThread.Resume;end;end; procedure Register;beginRegisterComponents('System', [TDirNotify]);end;end. 
      

  4.   

    需要用到一个未公开的API函数SHChangeNotifyRegister,你看以下例子你是否想为你的Windows加上一双眼睛,察看使用者在机器上所做的各种操作(例如建立、删除文件;改变文件或目录名字)呢?
    这里介绍一种利用Windows未公开函数实现这个功能的方法。
    在Windows下有一个未公开函数SHChangeNotifyRegister可以把你的窗口添加到系统的系统消息监视链中,该函数在Delphi中的定义如下:
    Function SHChangeNotifyRegister(hWnd,uFlags,dwEventID,uMSG,cItems:LongWord;
      lpps:PIDLSTRUCT):integer;stdcall;external 'Shell32.dll' index 2;
    其中参数hWnd定义了监视系统操作的窗口得句柄,参数uFlags dwEventID定义监视操作参数,参数uMsg定义操作消息,参数cItems定义附加参数,参数lpps指定一个PIDLSTRUCT结构,该结构指定监视的目录。
    当函数调用成功之后,函数会返回一个监视操作句柄,同时系统就会将hWnd指定的窗口加入到操作监视链中,当有文件操作发生时,系统会向hWnd发送uMsg指定的消息,我们只要在程序中加入该消息的处理函数就可以实现对系统操作的监视了。
    如果要退出程序监视,就要调用另外一个未公开得函数SHChangeNotifyDeregister来取消程序监视。
    下面是使用Delphi编写的具体程序实现范例,首先建立一个新的工程文件,然后在Form1中加入一个Button控件和一个Memo控件,
    程序的代码如下:unit Unit1;
    interface
    uses
    Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
    StdCtrls,shlobj,Activex;
    const
    SHCNE_RENAMEITEM = $1;
    SHCNE_CREATE = $2;
    SHCNE_DELETE = $4;
    SHCNE_MKDIR = $8;
    SHCNE_RMDIR = $10;
    SHCNE_MEDIAINSERTED = $20;
    SHCNE_MEDIAREMOVED = $40;
    SHCNE_DRIVEREMOVED = $80;
    SHCNE_DRIVEADD = $100;
    SHCNE_NETSHARE = $200;
    SHCNE_NETUNSHARE = $400;
    SHCNE_ATTRIBUTES = $800;
    SHCNE_UPDATEDIR = $1000;
    SHCNE_UPDATEITEM = $2000;
    SHCNE_SERVERDISCONNECT = $4000;
    SHCNE_UPDATEIMAGE = $8000;
    SHCNE_DRIVEADDGUI = $10000;
    SHCNE_RENAMEFOLDER =$20000;
    SHCNE_FREESPACE = $40000;
    SHCNE_ASSOCCHANGED = $8000000;
    SHCNE_DISKEVENTS = $2381F;
    SHCNE_GLOBALEVENTS = $C0581E0;
    SHCNE_ALLEVENTS = $7FFFFFFF;
    SHCNE_INTERRUPT = $80000000;
    SHCNF_IDLIST = 0;
    // LPITEMIDLIST
    SHCNF_PATHA = $1;
    // path name
    SHCNF_PRINTERA = $2;
    // printer friendly name
    SHCNF_DWORD = $3;
    // DWORD
    SHCNF_PATHW = $5;
    // path name
    SHCNF_PRINTERW = $6;
    // printer friendly name
    SHCNF_TYPE = $FF;
    SHCNF_FLUSH = $1000;
    SHCNF_FLUSHNOWAIT = $2000;
    SHCNF_PATH = SHCNF_PATHW;
    SHCNF_PRINTER = SHCNF_PRINTERW;
    WM_SHNOTIFY = $401;
    NOERROR = 0;
    type
    TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    private
    { Private declarations }
    procedure WMShellReg(var Message:TMessage);message WM_SHNOTIFY;
    public
    { Public declarations }
    end;
    type PSHNOTIFYSTRUCT=^SHNOTIFYSTRUCT;
    SHNOTIFYSTRUCT = record
    dwItem1 : PItemIDList;
    dwItem2 : PItemIDList;
    end;
    Type PSHFileInfoByte=^SHFileInfoByte;
    _SHFileInfoByte = record
    hIcon :Integer;
    iIcon :Integer;
    dwAttributes : Integer;
    szDisplayName : array [0..259] of char;
    szTypeName : array [0..79] of char;
    end;
    SHFileInfoByte=_SHFileInfoByte;
    Type PIDLSTRUCT = ^IDLSTRUCT;
    _IDLSTRUCT = record
    pidl : PItemIDList;
    bWatchSubFolders : Integer;
    end;
    IDLSTRUCT =_IDLSTRUCT;
    function SHNotify_Register(hWnd : Integer) : Bool;
    function SHNotify_UnRegister:Bool;
    function SHEventName(strPath1,strPath2:string;lParam:Integer):string;
    Function SHChangeNotifyDeregister(hNotify:integer):integer;stdcall;
    external 'Shell32.dll' index 4;
    Function SHChangeNotifyRegister(hWnd,uFlags,dwEventID,uMSG,cItems:LongWord;
    lpps:PIDLSTRUCT):integer;stdcall;external 'Shell32.dll' index 2;
    Function SHGetFileInfoPidl(pidl : PItemIDList;
    dwFileAttributes : Integer;
    psfib : PSHFILEINFOBYTE;
    cbFileInfo : Integer;
    uFlags : Integer):Integer;stdcall;
    external 'Shell32.dll' name 'SHGetFileInfoA';
    var
    Form1: TForm1;
    m_hSHNotify:Integer;
    m_pidlDesktop : PItemIDList;
    implementation
    {$R *.DFM}
    function SHEventName(strPath1,strPath2:string;lParam:Integer):string;
    var
    sEvent:String;
    begin
    case lParam of //根据参数设置提示消息
    SHCNE_RENAMEITEM: sEvent := '重命名文件'+strPath1+'为'+strpath2;
    SHCNE_CREATE: sEvent := '建立文件 文件名:'+strPath1;
    SHCNE_DELETE: sEvent := '删除文件 文件名:'+strPath1;
    SHCNE_MKDIR: sEvent := '新建目录 目录名:'+strPath1;
    SHCNE_RMDIR: sEvent := '删除目录 目录名:'+strPath1;
    SHCNE_MEDIAINSERTED: sEvent := strPath1+'中插入可移动存储介质';
    SHCNE_MEDIAREMOVED: sEvent := strPath1+'中移去可移动存储介质'+strPath1+' '+strpath2;
    SHCNE_DRIVEREMOVED: sEvent := '移去驱动器'+strPath1;
    SHCNE_DRIVEADD: sEvent := '添加驱动器'+strPath1;
    SHCNE_NETSHARE: sEvent := '改变目录'+strPath1+'的共享属性';
    SHCNE_ATTRIBUTES: sEvent := '改变文件目录属性 文件名'+strPath1;
    SHCNE_UPDATEDIR: sEvent := '更新目录'+strPath1;
    SHCNE_UPDATEITEM: sEvent := '更新文件 文件名:'+strPath1;
    SHCNE_SERVERDISCONNECT: sEvent := '断开与服务器的连接'+strPath1+' '+strpath2;
    SHCNE_UPDATEIMAGE: sEvent := 'SHCNE_UPDATEIMAGE';
    SHCNE_DRIVEADDGUI: sEvent := 'SHCNE_DRIVEADDGUI';
    SHCNE_RENAMEFOLDER: sEvent := '重命名文件夹'+strPath1+'为'+strpath2;
    SHCNE_FREESPACE: sEvent := '磁盘空间大小改变';
    SHCNE_ASSOCCHANGED: sEvent := '改变文件关联';
    else
    sEvent:='未知操作'+IntToStr(lParam);
    end;
    Result:=sEvent;
    end;
    function SHNotify_Register(hWnd : Integer) : Bool;
    var
    ps:PIDLSTRUCT;
    begin
    {$R-}
    Result:=False;
    If m_hSHNotify = 0 then begin
    //获取桌面文件夹的Pidl
    if SHGetSpecialFolderLocation(0, CSIDL_DESKTOP,
    m_pidlDesktop)<> NOERROR then
    Form1.close;
    if Boolean(m_pidlDesktop) then begin
    ps.bWatchSubFolders := 1;
    ps.pidl := m_pidlDesktop;
    // 利用SHChangeNotifyRegister函数注册系统消息处理
    m_hSHNotify := SHChangeNotifyRegister(hWnd, (SHCNF_TYPE Or SHCNF_IDLIST),
    (SHCNE_ALLEVENTS Or SHCNE_INTERRUPT),
    WM_SHNOTIFY, 1, ps);
    Result := Boolean(m_hSHNotify);
    end
    Else
    // 如果出现错误就使用 CoTaskMemFree函数来释放句柄
    CoTaskMemFree(m_pidlDesktop);
    End;
    {$R+}
    end;
    function SHNotify_UnRegister:Bool;
    begin
    Result:=False;
    If Boolean(m_hSHNotify) Then
    //取消系统消息监视,同时释放桌面的Pidl
    If Boolean(SHChangeNotifyDeregister(m_hSHNotify)) Then begin
    {$R-}
    m_hSHNotify := 0;
    CoTaskMemFree(m_pidlDesktop);
    Result := True;
    {$R-}
    End;
    end;
    procedure TForm1.WMShellReg(var Message:TMessage); //系统消息处理函数
    var
    strPath1,strPath2:String;
    charPath:array[0..259]of char;
    pidlItem:PSHNOTIFYSTRUCT;
    begin
    pidlItem:=PSHNOTIFYSTRUCT(Message.wParam);
    //获得系统消息相关得路径
    SHGetPathFromIDList(pidlItem.dwItem1,charPath);
    strPath1:=charPath;
    SHGetPathFromIDList(pidlItem.dwItem2,charPath);
    strPath2:=charPath;
    Memo1.Lines.Add(SHEvEntName(strPath1,strPath2,Message.lParam)+chr(13)+chr(10));
    end;
    procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
    begin
    //在程序退出的同时删除监视
    if Boolean(m_pidlDesktop) then
    SHNotify_Unregister;
    end;
    procedure TForm1.Button1Click(Sender: TObject); //Button1的Click消息
    begin
    m_hSHNotify:=0;
    if SHNotify_Register(Form1.Handle) then begin //注册Shell监视
    ShowMessage('Shell监视程序成功注册');
    Button1.Enabled := False;
    end
    else
    ShowMessage('Shell监视程序注册失败');
    end;
    procedure TForm1.FormCreate(Sender: TObject);
    begin
    Button1.Caption := '打开监视';
    end;
    end.
    运行程序,点击“打开监视”按钮,如果出现一个显示“Shell监视程序成功注册”的对话框,说明Form1已经加入到系统操作监视链中了,你可以试着在资源管理器中建立、删除文件夹,移动文件等操作,你可以发现这些操作都被记录下来并显示在文本框中。
    在上面的程序中多次使用到了一个PItemIDList的结构,这个数据结构指定Windows下得一个“项目”,在Windows下资源实现统一管理一个“项目”可以是一个文件或者一个文件夹,也可以是一个打印机等资源。另外一些API函数也涉及到了Shell(Windows外壳)操作,各位读者可以参考相应的参考资料。