复制文件时如何调用取消? (将复制文件ex函数与复制进度例程回调函数一起使用)

时间:2019-04-01 09:01:43

标签: c++ winapi mfc

我创建了一个取消按钮来停止文件复制。我应该在“复制进度例程”中调用什么才能取消文件复制。

DWORD CALLBACK CopyProgressRoutine(LARGE_INTEGER TotalFileSize, 
LARGE_INTEGER TotalBytesTransferred, LARGE_INTEGER StreamSize, 
LARGE_INTEGER StreamBytesTransferred, DWORD dwStreamNumber, DWORD 
dwCallbackReason, HANDLE hSourceFile, HANDLE hDestinationFile, LPVOID 
lpData)
{   
HWND hWndDlg = (HWND)lpData;
static HWND hwndIDC_PROGRESS1;
hwndIDC_PROGRESS1 = GetDlgItem(hWndDlg, IDC_PROGRESS_DATA_OF_RETRIEVING);

DOUBLE Percentage = ((DOUBLE)TotalBytesTransferred.QuadPart / 
    (DOUBLE)TotalFileSize.QuadPart) * 100;

switch (dwCallbackReason)
{
    case CALLBACK_CHUNK_FINISHED:
    break;

    case CALLBACK_STREAM_SWITCH:
    if (cancel_Copy_File!=false) // cancel_copy_file is still undefined
        {
            return PROGRESS_CANCEL;
        }
    break;
}
return PROGRESS_CONTINUE;

2 个答案:

答案 0 :(得分:2)

您需要从PROGRESS_CANCEL返回CopyProgressRoutine,如下所述: LPPROGRESS_ROUTINE回调函数 https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nc-winbase-lpprogress_routine

返回值:

PROGRESS_CANCEL取消复制操作并删除目标文件。

PROGRESS_CONTINUE继续复制操作。

请参阅MSDN文章中的完整列表。

答案 1 :(得分:2)

您只会对CALLBACK_STREAM_SWITCH做出反应,在大多数情况下,您只会得到一次。 CopyFileEx分块复制文件,并且在每个块用reson == CALLBACK_CHUNK_FINISHED调用回调之后。实际上,您无需区分这两种情况并使用相同的代码处理这两种情况。

DWORD CALLBACK CopyProgressRoutine(LARGE_INTEGER TotalFileSize, 
    LARGE_INTEGER TotalBytesTransferred, LARGE_INTEGER StreamSize, 
    LARGE_INTEGER StreamBytesTransferred, DWORD dwStreamNumber, DWORD 
    dwCallbackReason, HANDLE hSourceFile, HANDLE hDestinationFile, LPVOID 
    lpData)
{   
    HWND hWndDlg = (HWND)lpData;
    static HWND hwndIDC_PROGRESS1;
    hwndIDC_PROGRESS1 = GetDlgItem(hWndDlg, IDC_PROGRESS_DATA_OF_RETRIEVING);

    DOUBLE Percentage = ((DOUBLE)TotalBytesTransferred.QuadPart / 
        (DOUBLE)TotalFileSize.QuadPart) * 100;

    /* If you copy on GUI thread, you need to pump messages with
       while ( PeekMessage( ... ) ) { ... }
    */

    return cancel_Copy_File ? PROGRESS_CANCEL : PROGRESS_CONTINUE;
}