监控文件变化的三种方法

=================================================================

通过 未公开API SHChangeNotifyRegister 实现

=================================================================


一、原理

Windows 内部有两个未公开的函数(注:在最新的MSDN中,已经公开了这两个函数),分别叫做SHChangeNotifyRegister和 SHChangeNotifyDeregister,可以实现以上的功能。这两个函数位于Shell32.dll中,是用序号方式导出的。这就是为什么我们用VC自带的Depends工具察看Shell32.dll时,找不到这两个函数的原因。SHChangeNotifyRegister的导出序号是 2;而SHChangeNotifyDeregister的导出序号是4。
SHChangeNotifyRegister可以把指定的窗口添加到系统的消息监视链中,这样窗口就能接收到来自文件系统或者Shell的通知了。而对应的另一个函数,SHChangeNotifyDeregister,则用来取消监视钩挂。SHChangeNotifyRegister的原型和相关参数如下:
  1. ULONG SHChangeNotifyRegister  
  2. (          
  3.     HWND hwnd,  
  4.     int   fSources,  
  5.     LONG fEvents,  
  6.     UINT    wMsg,  
  7.     Int cEntries,  
  8.     SHChangeNotifyEntry *pfsne  
  9. );  
其中:
hwnd
将要接收改变或通知消息的窗口的句柄。
fSource
指示接收消息的事件类型,将是下列值的一个或多个(注:这些标志没有被包括在任何头文件中,使用者须在自己的程序中加以定义或者直接使用其对应的数值)
SHCNRF_InterruptLevel
0x0001。接收来自文件系统的中断级别通知消息。
SHCNRF_ShellLevel
0x0002。接收来自Shell的Shell级别通知消息。
SHCNRF_RecursiveInterrupt
0x1000。接收目录下所有子目录的中断事件。此标志必须和SHCNRF_InterruptLevel 标志合在一起使用。当使用该标志时,必须同时设置对应的SHChangeNotifyEntry结构体中的fRecursive成员为TRUE(此结构体由函数的最后一个参数pfsne指向),这样通知消息在目录树上是递归的。
SHCNRF_NewDelivery
0x8000。接收到的消息使用共享内存。必须先调用SHChangeNotification_Lock,然后才能存取实际的数据,完成后调用SHChangeNotification_Unlock函数释放内存。
fEvents
要捕捉的事件,其所有可能的值请参见MSDN中关于SHChangeNotify函数的注解。
wMsg
产生对应的事件后,发往窗口的消息。
cEntries
pfsne指向的数组的成员的个数。
pfsne
SHChangeNotifyEntry 结构体数组的起始指针。此结构体承载通知消息,其成员个数必须设置成1,否则SHChangeNotifyRegister或者 SHChangeNotifyDeregister将不能正常工作(但是据我试验,如果cEntries设为大于1的值,依然可以注册成功,不知何故)。
如果函数调用成功,则返回一个整型注册标志号,否则将返回0。同时系统就会将hwnd指定的窗口加入到操作监视链中,当有文件操作发生时,系统会向hwnd标识的窗口发送wMsg指定的消息,我们只要在程序中加入对该消息的处理函数就可以实现对系统操作的监视了。
如果要退出程序监视,就要调用另外一个未公开得函数SHChangeNotifyDeregister来取消程序监视。该函数的原型如下:
BOOL SHChangeNotifyDeregister(ULONG ulID);

其中ulID指定了要注销的监视注册标志号,如果卸载成功,返回TRUE,否则返回FALSE。


二、实例


在使用这两个函数之前,必须要先声明它们的原型,同时还要添加一些宏和结构定义。我们在原工程中添加一个ShellDef.h头文件,然后加入如下声明:
  1. #define SHCNRF_InterruptLevel 0x0001 //Interrupt level notifications from the file system  
  2. #define SHCNRF_ShellLevel   0x0002 //Shell-level notifications from the shell  
  3. #define SHCNRF_RecursiveInterrupt 0x1000 //Interrupt events on the whole subtree  
  4. #define SHCNRF_NewDelivery   0x8000 //Messages received use shared memory  
  5.   
  6. typedef struct  
  7. {  
  8.     LPCITEMIDLIST pidl; //Pointer to an item identifier list (PIDL) for which to receive notifications  
  9.     BOOL fRecursive; //Flag indicating whether to post notifications for children of this PIDL  
  10. }SHChangeNotifyEntry;  
  11.   
  12. typedef struct  
  13. {  
  14.     DWORD dwItem1; // dwItem1 contains the previous PIDL or name of the folder.  
  15.     DWORD dwItem2; // dwItem2 contains the new PIDL or name of the folder.  
  16. }SHNotifyInfo;  
  17.   
  18. typedef ULONG (WINAPI* pfnSHChangeNotifyRegister)  
  19. (  
  20.   HWND hWnd,  
  21.   int fSource,  
  22.   LONG fEvents,  
  23.   UINT wMsg,  
  24.   int cEntries,  
  25.   SHChangeNotifyEntry* pfsne  
  26. );  
  27.   
  28. typedef BOOL (WINAPI* pfnSHChangeNotifyDeregister)(ULONG ulID);  
这些宏和函数的声明,以及参数含义,如前所述。下面我们要在CListCtrlEx体内添加两个函数指针和一个ULONG型的成员变量,以保存函数地址和返回的注册号。
接下来实现一个函数Initialize,在其中,我们首先进行加载Shell32.dll以及初始化函数指针动作,接着调用注册函数向Shell注册。
  1. BOOL Initialize()  
  2. {  
  3.   …………  
  4.   //加载Shell32.dll  
  5.   m_hShell32 = LoadLibrary("Shell32.dll");  
  6.   if(m_hShell32 == NULL)  
  7.   {  
  8.     return FALSE;  
  9.   }  
  10.   
  11.   //取函数地址  
  12.   m_pfnDeregister = NULL;  
  13.   m_pfnRegister = NULL;  
  14.   m_pfnRegister = (pfnSHChangeNotifyRegister)GetProcAddress(m_hShell32,MAKEINTRESOURCE(2));  
  15.   m_pfnDeregister = (pfnSHChangeNotifyDeregister)GetProcAddress(m_hShell32,MAKEINTRESOURCE(4));  
  16.   if(m_pfnRegister==NULL || m_pfnDeregister==NULL)  
  17.   {  
  18.     return FALSE;  
  19.   }  
  20.   
  21.   SHChangeNotifyEntry shEntry = {0};  
  22.   shEntry.fRecursive = TRUE;  
  23.   shEntry.pidl = 0;  
  24.   m_ulNotifyId = 0;  
  25.   
  26.   //注册Shell监视函数  
  27.   m_ulNotifyId = m_pfnRegister(  
  28.         GetSafeHwnd(),  
  29.         SHCNRF_InterruptLevel|SHCNRF_ShellLevel,  
  30.         SHCNE_ALLEVENTS,  
  31.         WM_USERDEF_FILECHANGED, //自定义消息  
  32.         1,  
  33.         &shEntry  
  34.        );  
  35.   if(m_ulNotifyId == 0)  
  36.   {  
  37.     MessageBox("Register failed!","ERROR",MB_OK|MB_ICONERROR);  
  38.     return FALSE;  
  39.   }  
  40.   return TRUE;  
  41. }  

=================================================================

通过 FindFirstChangeNotification 实现

=================================================================


FindFirstChangeNotification函数创建一个更改通知句柄并设置初始更改通知过滤条件。
当一个在指定目录或子目录下发生的更改符合过滤条件时,等待通知句柄则成功。
该函数原型为:
  1. HANDLE FindFirstChangeNotification(  
  2. LPCTSTR lpPathName, //目录名  
  3. BOOL bWatchSubtree, // 监视选项  
  4. DWORD dwNotifyFilter // 过滤条件  
  5. );  
当下列情况之一发生时,WaitForMultipleObjects函数返回
1.一个或者全部指定的对象在信号状态(signaled state)
2.到达超时间隔

例程如下:
  1. DWORD dwWaitStatus;  
  2. HANDLE dwChangeHandles[2];  
  3.   
  4. //监视C:\Windows目录下的文件创建和删除  
  5.   
  6. dwChangeHandles[0] = FindFirstChangeNotification(  
  7. "C:\\WINDOWS"// directory to watch  
  8. FALSE, // do not watch the subtree  
  9. FILE_NOTIFY_CHANGE_FILE_NAME); // watch file name changes  
  10.   
  11. if (dwChangeHandles[0] == INVALID_HANDLE_VALUE)  
  12. ExitProcess(GetLastError());  
  13.   
  14. //监视C:\下子目录树的文件创建和删除  
  15.   
  16. dwChangeHandles[1] = FindFirstChangeNotification(  
  17. "C:\\"// directory to watch  
  18. TRUE, // watch the subtree  
  19. FILE_NOTIFY_CHANGE_DIR_NAME); // watch dir. name changes  
  20.   
  21. if (dwChangeHandles[1] == INVALID_HANDLE_VALUE)  
  22.   ExitProcess(GetLastError());  
  23.   
  24. // Change notification is set. Now wait on both notification  
  25. // handles and refresh accordingly.  
  26.   
  27. while (TRUE)  
  28. {  
  29.   
  30.   // Wait for notification.  
  31.   
  32.   dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles,FALSE, INFINITE);  
  33.   
  34.   switch (dwWaitStatus)  
  35.   {  
  36.    case WAIT_OBJECT_0:  
  37.   
  38.     //在C:\WINDOWS目录中创建或删除文件 。  
  39.    //刷新该目录及重启更改通知(change notification).  
  40.   
  41.    AfxMessageBox("RefreshDirectory");  
  42.    if ( FindNextChangeNotification(dwChangeHandles[0]) == FALSE )  
  43.    ExitProcess(GetLastError());  
  44.    break;  
  45.   
  46.   case WAIT_OBJECT_0 1:  
  47.    //在C:\WINDOWS目录中创建或删除文件 。  
  48.    //刷新该目录树及重启更改通知(change notification).  
  49.   
  50.    AfxMessageBox("RefreshTree");  
  51.    if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE)  
  52.    ExitProcess(GetLastError());  
  53.    break;  
  54.   
  55.   default:  
  56.    ExitProcess(GetLastError());  
  57.   }  
  58. }  

=================================================================

通过 ReadDirectoryChangesW 实现

=================================================================


  1. bool Monitor()  
  2. {  
  3.      
  4.      
  5.     HANDLE hFile   =   CreateFile(  
  6.         "c:\\",  
  7.         GENERIC_READ|GENERIC_WRITE,  
  8.         FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,  
  9.         NULL,  
  10.         OPEN_EXISTING,  
  11.         FILE_FLAG_BACKUP_SEMANTICS,  
  12.         NULL  
  13.         );  
  14.     if(   INVALID_HANDLE_VALUE   ==   hFile   )   return   false;  
  15.      
  16.     char   buf[   2*(sizeof(FILE_NOTIFY_INFORMATION)+MAX_PATH)   ];  
  17.     FILE_NOTIFY_INFORMATION*   pNotify=(FILE_NOTIFY_INFORMATION   *)buf;  
  18.     DWORD   BytesReturned;  
  19.     while(true)  
  20.     {  
  21.         if(   ReadDirectoryChangesW(   hFile,  
  22.             pNotify,  
  23.             sizeof(buf),  
  24.             true,  
  25.             FILE_NOTIFY_CHANGE_FILE_NAME|  
  26.             FILE_NOTIFY_CHANGE_DIR_NAME|  
  27.             FILE_NOTIFY_CHANGE_ATTRIBUTES|  
  28.             FILE_NOTIFY_CHANGE_SIZE|  
  29.             FILE_NOTIFY_CHANGE_LAST_WRITE|  
  30.             FILE_NOTIFY_CHANGE_LAST_ACCESS|  
  31.             FILE_NOTIFY_CHANGE_CREATION|  
  32.             FILE_NOTIFY_CHANGE_SECURITY,  
  33.             &BytesReturned,  
  34.             NULL,  
  35.             NULL   )   )  
  36.         {  
  37.             char   tmp[MAX_PATH],   str1[MAX_PATH],   str2[MAX_PATH];  
  38.             memset(   tmp,   0,   sizeof(tmp)   );  
  39.             WideCharToMultiByte(   CP_ACP,0,pNotify->FileName,pNotify->FileNameLength/2,tmp,99,NULL,NULL   );  
  40.             strcpy(   str1,   tmp   );  
  41.              
  42.             if(   0   !=   pNotify->NextEntryOffset   )  
  43.             {  
  44.                 PFILE_NOTIFY_INFORMATION   p   =   (PFILE_NOTIFY_INFORMATION)((char*)pNotify+pNotify->NextEntryOffset);  
  45.                 memset(   tmp,   0,   sizeof(tmp)   );  
  46.                 WideCharToMultiByte(   CP_ACP,0,p->FileName,p->FileNameLength/2,tmp,99,NULL,NULL   );  
  47.                 strcpy(   str2,   tmp   );  
  48.             }  
  49.              
  50.             // your process  
  51.         }  
  52.         else  
  53.         {  
  54.             break;  
  55.         }  
  56.     }  
  57.   
  58.     return true;  
  59. }  
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值