bool DeleteFolderContents(LPCTSTR szFolder, BOOL bIncludeSubFolders, LPCTSTR szFileMask, HANDLE hTerminate, BOOL bProcessMsgLoop)
{
// if the dir does not exists just return
DWORD dwAttr = GetFileAttributes(szFolder);
if (dwAttr == 0xffffffff || !(dwAttr & FILE_ATTRIBUTE_DIRECTORY))
return false;
// if a file mask has been specified with subfolders we need to do 2 passes on each folder,
// one for the files and one for the sub folders
int nPasses = (bIncludeSubFolders && (szFileMask && lstrlen(szFileMask))) ? 2 : 1;
bool bResult = true;
bool bStopped = (WaitForSingleObject(hTerminate, 0) == WAIT_OBJECT_0);
for (int nPass = 0; !bStopped && nPass < nPasses; nPass++)
{
CString sSearchSpec(szFolder), sMask(szFileMask);
if (sMask.IsEmpty() || nPass == 1) // (nPass == 1) == 2nd pass (for folders)
sMask = "*.*";
TerminatePath(sSearchSpec);
sSearchSpec += sMask;
WIN32_FIND_DATA finfo;
HANDLE hSearch = NULL;
if ((hSearch = FindFirstFile(sSearchSpec, &finfo)) != INVALID_HANDLE_VALUE)
{
do
{
if (bProcessMsgLoop)
** ProcessMsgLoop();**
if (finfo.cFileName[0] != '.')
{
CString sItem(szFolder);
sItem += "\\";
sItem += finfo.cFileName;
if (finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (bIncludeSubFolders && (nPass == 1 || nPasses == 1))
{
if (DeleteFolderContents(sItem, TRUE, szFileMask, hTerminate, bProcessMsgLoop))
{
if (!szFileMask || !lstrlen(szFileMask))
bResult = (RemoveDirectory(sItem) == TRUE);
}
}
}
else
bResult = (DeleteFile(sItem) == TRUE);
}
bStopped = (WaitForSingleObject(hTerminate, 0) == WAIT_OBJECT_0);
} while (!bStopped && bResult && FindNextFile(hSearch, &finfo));
FindClose(hSearch);
}
}
return (!bStopped && bResult);
}
void ProcessMsgLoop()
{
MSG msg;
while (::PeekMessage((LPMSG)&msg, NULL, 0, 0, PM_REMOVE))
{
if (IsDialogMessage(msg.hwnd, (LPMSG)&msg))
{
// do nothing - its already been done
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}