界面如下:
关键代码如下:
1 BOOL bRet = FALSE; 2 BYTE Buffer[1024] = {0}; 3 4 CDirectoryWatchDlg *pDlg = (CDirectoryWatchDlg *)lpParam; 5 FILE_NOTIFY_INFORMATION *pBuffer = (FILE_NOTIFY_INFORMATION*)Buffer; 6 DWORD dwBytesReturned = 0; 7 HANDLE hFile = CreateFile(pDlg->m_strDirectoryPath.GetBuffer(0), FILE_LIST_DIRECTORY, FILE_SHARE_READ 8 | FILE_SHARE_DELETE | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); 9 if(INVALID_HANDLE_VALUE == hFile) 10 { 11 DWORD dwErr = GetLastError(); 12 CString strErr; 13 strErr.Format(_T("CreateFile Error : %d"), dwErr); 14 AfxMessageBox(strErr); 15 return 1; 16 } 17 18 if (pDlg->GetDlgItem(IDC_BUTTON_START) != NULL) 19 { 20 pDlg->GetDlgItem(IDC_BUTTON_START)->EnableWindow(FALSE); 21 } 22 if (pDlg->GetDlgItem(IDC_BUTTON_STOP) != NULL) 23 { 24 pDlg->GetDlgItem(IDC_BUTTON_STOP)->EnableWindow(TRUE); 25 } 26 27 CString strInfo; 28 CString strType; 29 CString strIndex; 30 31 while (TRUE) 32 { 33 ZeroMemory(Buffer, 1024); 34 bRet = ReadDirectoryChangesW(hFile, &Buffer, sizeof(Buffer), TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | 35 FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_LAST_WRITE, &dwBytesReturned, NULL, NULL); 36 if (bRet == TRUE) 37 { 38 switch (pBuffer->Action) 39 { 40 case FILE_ACTION_ADDED: 41 strType = _T("添加"); 42 strInfo = _T("添加文件:"); 43 strInfo += pBuffer->FileName; 44 break; 45 case FILE_ACTION_REMOVED: 46 strType = _T("删除"); 47 strInfo = _T("删除文件:"); 48 strInfo += pBuffer->FileName; 49 break; 50 case FILE_ACTION_MODIFIED: 51 strType = _T("修改"); 52 strInfo = _T("修改文件:"); 53 strInfo += pBuffer->FileName; 54 break; 55 case FILE_ACTION_RENAMED_OLD_NAME: 56 strType = _T("重命名"); 57 strInfo = _T("将文件"); 58 strInfo += pBuffer->FileName; 59 if (pBuffer->NextEntryOffset != 0) 60 { 61 FILE_NOTIFY_INFORMATION *TempBuffer = (FILE_NOTIFY_INFORMATION*)((DWORD)pBuffer + pBuffer->NextEntryOffset); 62 switch (TempBuffer->Action) 63 { 64 case FILE_ACTION_RENAMED_NEW_NAME: 65 strInfo += _T("重命名为"); 66 strInfo += TempBuffer->FileName; 67 break; 68 } 69 } 70 break; 71 case FILE_ACTION_RENAMED_NEW_NAME: 72 strType = _T("重命名"); 73 strInfo = _T("重命名为"); 74 strInfo += pBuffer->FileName; 75 break; 76 } 77 78 if (pDlg != NULL) 79 { 80 strIndex.Format(_T("%d"), pDlg->nIndex); 81 pDlg->m_ctrlDirectoryWatchLog.InsertItem(pDlg->nIndex, strIndex); 82 pDlg->m_ctrlDirectoryWatchLog.SetItemText(pDlg->nIndex, 1, strType); 83 pDlg->m_ctrlDirectoryWatchLog.SetItemText(pDlg->nIndex++, 2, strInfo); 84 } 85 } 86 } 87 88 CloseHandle(hFile); 89 return 0;