在资源管理器中,删除一个文件,更改一个文件夹名称,都能及时刷新。这是怎么做到的呢?答案是使用了文件改变通知。
先看一个结构
typedef struct tagSHCHANGENOTIFYENTRY {
DWORD dwEventMask;
LPTSTR pszWatchDir;
BOOL fRecursive;
} SHCHANGENOTIFYENTRY;
要接收文件改变的消息,我们要使用一个窗口hWnd,在窗口创建的WM_CREATE消息处注册:
SHCHANGENOTIFYENTRY schneNotifyEntry;
schneNotifyEntry.dwEventMask = SHCNE_ALLEVENTS;//监视所有事件
schneNotifyEntry.pszWatchDir = NULL;//要监视的目录名,NULL表示所有
schneNotifyEntry.fRecursive = TRUE;//监视目录时,是否递归
SHChangeNotifyRegister(hWnd, &schneNotifyEntry);
在窗口的过程函数里,我们响应WM_FILECHANGEINFO消息
case WM_FILECHANGEINFO:
{
FILECHANGENOTIFY *lpfcn;
FILECHANGEINFO *lpfci;
lpfcn = (FILECHANGENOTIFY *)lParam;
if (NULL == lpfcn)
{
break;
}
lpfci = &(lpfcn->fci);
if (NULL == lpfci)
{
break;
}
else
{
if (FALSE == SHCNEEvent(lpfci))
{
MessageBox(TEXT("SCHNE Event failed"), TEXT("Error"), MB_OK);
}
}
SHChangeNotifyFree(lpfcn);
}
break;
SHCNEEvent函数实现如下:
BOOL SHCNEEvent(FILECHANGEINFO *lpfci)
{
//lpfci->wEventId,事件
//lpfci->dwItem1,旧的文件或目录名
//lpfci->dwItem2,新的文件或目录名
//lpfci->dwAttributes,文件或目录特性
//lpfci->ftModified,文件改变时的时间
//lpfci->nFileSize,文件大小
switch (lpfci->wEventId)
{
case SHCNE_RENAMEITEM:
break;
case SHCNE_CREATE:
break;
case SHCNE_DELETE:
break;
case SHCNE_MKDIR:
break;
case SHCNE_RMDIR:
break;
case SHCNE_MEDIAINSERTED:
break;
case SHCNE_MEDIAREMOVED:
break;
case SHCNE_DRIVEADD:
break;
case SHCNE_DRIVEREMOVED:
break;
case SHCNE_NETSHARE:
break;
case SHCNE_NETUNSHARE:
break;
case SHCNE_ATTRIBUTES:
break;
case SHCNE_UPDATEDIR:
break;
case SHCNE_SERVERDISCONNECT:
break;
case SHCNE_RENAMEFOLDER:
break;
default:
break;
}
return TRUE;
}
根据事件,就可以知道是哪个文件或目录发生了改变。
最后,在hWnd销毁处,要注销:
SHChangeNotifyDeregister(hWnd);