Hi everyone, please can anyone show me how to show a progress bar while copying a file. I tried using SetTimer() but i does not work the way i want it i.e the file gets copied after the given time has finished.

Dani AI

Generated

This problem almost always comes from doing the copy on the UI thread. A UI timer won’t fire while a long synchronous copy blocks the message loop, so the progress control only updates after the copy finishes. was on the right track about the progress control; was also correct to point out a callback-style API. Two reliable patterns that avoid blocking the UI are shown below.

One approach: run the copy in a worker thread and post progress to the window. The worker reads/writes the file in chunks, keeps a 64-bit byte-count, computes percent = (copied * 100) / total, and uses PostMessage to send that percent to the main window. The main thread handles the custom message and sets the progress control position (only the UI thread should touch controls). Example sketch:

#define WM_APP_PROGRESS (WM_APP + 1)

DWORD WINAPI CopyThread(LPVOID p)
{
    HWND hwnd = (HWND)p;
    HANDLE hSrc = CreateFile(...), hDst = CreateFile(...);
    LARGE_INTEGER total; GetFileSizeEx(hSrc, &total);
    BYTE buf[64*1024];
    ULONGLONG copied = 0;
    DWORD r,w;
    while (ReadFile(hSrc, buf, sizeof(buf), &r, NULL) && r) {
        WriteFile(hDst, buf, r, &w, NULL);
        copied += w;
        int pct = (int)((copied * 100) / total.QuadPart);
        PostMessage(hwnd, WM_APP_PROGRESS, (WPARAM)pct, 0);
        if (cancelRequested()) break;
    }
    CloseHandle(hSrc); CloseHandle(hDst);
    PostMessage(hwnd, WM_APP_PROGRESS, (WPARAM)100, 0);
    return 0;
}

/* In WndProc: on WM_APP_PROGRESS call SendMessage(progressHandle, PBM_SETPOS, wParam, 0); */

Notes and gotchas:

  • Use a large buffer (32–128 KB) for throughput.
  • Use 64-bit arithmetic for files >4GB.
  • Never update controls from the worker thread; always post to the UI thread.
  • Support cancellation with an event or flag checked in the loop.
  • Alternatively, use the OS copy function that offers progress callbacks (invoke the callback on a background thread or post from it to the UI).

These patterns will give smooth, real-time progress without freezing the GUI.

Recommended Answers

All 2 Replies

I am not sure about your code but you should put following code in constructor or init method,

m_progress.SetRange(0,100); 
m_progress.SetPos(0);

and StepIt() in a timer procedure,

m_progress.StepIt()

What functions are you using to do the copying? win32 api will call your function for each portion of the file that has been copied, allowing it to update the progress bar.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.