BOOL WINAPI SHChangeNotifyRegister(
HWNDhwnd,
SHCHANGENOTIFYENTRY * pshcne
);
第一个参数需要一个窗口句柄,用CreateWindow()方法可以创建一个窗口(创建窗口前需要调用RegisterClass()方法,在RegisterClass这个参数中需要传入实现我们自己的消息处理函数WindowProc())。
第二个参数是注册我们需要获取的通知消息。
上面这些处理完成过后,我们就可以用GetMessage()来获取系统给我们的通知消息了。
窗口消息中有很多其他我们不想要的消息,在此处我们关心的是 WM_FILECHANGEINFO(33025) 消息。对此消息做处理:
FILECHANGENOTIFY *lpfcn = NULL;
FILECHANGEINFO *lpfci = NULL;
lpfcn = (FILECHANGENOTIFY *)lParam;//lParam是这个消息处理函数传入的参数。
lpfci = &(lpfcn->fci);
switch(lpfci->wEventId)
{
case SHCNE_CREATE://消息通知事件
break;
.....
}
不在做说明,可以看 FILECHANGENOTIFY 介绍。
在处理结束后需要调用SHChangeNotifyFree(lpfcn)释放资源。
相关代码:
- BOOL LogSHCNEEvent(FILECHANGEINFO *lpfci)
- {
- WCHAR *path1 = NULL;
- WCHAR *path2 = NULL;
- switch(lpfci->wEventId)
- {
- case SHCNE_RENAMEITEM:
- break;
- case SHCNE_CREATE:
- break;
- //.......//other message
- }
- //....
- }
- LRESULT CALLBACK WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
- {
- // Structures for handling the File Change Information
- FILECHANGENOTIFY *lpfcn = NULL;
- FILECHANGEINFO *lpfci = NULL;
- switch(Msg)
- {
- case WM_FILECHANGEINFO:
- // see if the pointer to the file change notify struct is valid
- lpfcn = (FILECHANGENOTIFY *)lParam;
- if (NULL == lpfcn)
- {
- break;
- }
- // see if the pointer to the file change info structure
- lpfci = &(lpfcn->fci);
- if (NULL == lpfci)
- {
- break;
- }
- else
- {
- if (FALSE == LogSHCNEEvent(lpfci))
- {
- MessageBox(hWnd, TEXT("SCHNE Event was not logged"), TEXT("Program Error"), MB_OK);
- }
- }
- SHChangeNotifyFree(lpfcn);
- break;
- }
- }
- ATOM MyRegisterClass(LPTSTR szWindowClass)
- {
- WNDCLASS wc;
- wc.style = CS_HREDRAW | CS_VREDRAW;
- wc.lpfnWndProc = WindowProc;
- wc.cbClsExtra = 0;
- wc.cbWndExtra = 0;
- wc.hInstance = NULL;
- wc.hIcon = NULL;
- wc.hCursor = 0;
- wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
- wc.lpszMenuName = 0;
- wc.lpszClassName = szWindowClass;
- return RegisterClass(&wc);
- }
- void ParseMessage()
- {
- MSG msg;
- while (TRUE)
- {
- GetMessage(&msg, NULL, 0, 0);
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
- }
- DWORD SHNCInit()
- {
- BOOL bl_ret = FALSE;
- WCHAR *winClass = _T("console");
- WCHAR *title = _T("notify");
- DWORD dw_error = 0;
- SHCHANGENOTIFYENTRY pshcne;
- if(0 == MyRegisterClass(winClass))
- {
- dw_error = GetLastError();
- return dw_error;
- }
- g_hWnd = CreateWindow(winClass, title, WS_VISIBLE,
- CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
- NULL, NULL, (HINSTANCE)GetCurrentProcess(), NULL);
- if (NULL == g_hWnd)
- {
- dw_error = GetLastError();
- return dw_error;
- }
- pshcne.dwEventMask = SHCNE_ALLEVENTS;
- pshcne.pszWatchDir = NULL;
- pshcne.fRecursive = TRUE;
- bl_ret = SHChangeNotifyRegister(g_hWnd, &pshcne);
- if (FALSE == bl_ret)
- {
- dw_error = GetLastError();
- return dw_error;
- }
- return 0;
- }
- void SHNCListener()
- {
- DWORD dw_error = 0;
- dw_error = SHNCInit();
- ParseMessage();
- }