About the issue with MFC multithreaded progress bar

In MFC, implementing a progress bar using multiple threads can be achieved through the following steps:

  1. Create a progress bar control using the CProgressCtrl class provided by MFC.
  2. Create a custom thread class that inherits from CWinThread and override the Run method. Implement the tasks that need to be executed in the background within the Run method, and update the progress bar control at appropriate times.
  3. Instantiate a custom thread class in the main thread and call its CreateThread method to start the thread.
  4. To update the progress bar, send a custom message to the main window to notify the main thread to update the value of the progress bar control.

The specific implementation code is shown below:

// 主线程代码
void CMyDialog::OnButtonStart()
{
    // 创建进度条
    m_progressBar.Create(WS_CHILD | WS_VISIBLE | PBS_SMOOTH, CRect(10, 10, 200, 30), this, IDC_PROGRESS_BAR);

    // 创建自定义线程类的实例
    m_thread = new CMyThread();

    // 启动线程
    m_thread->CreateThread();

    // 注册自定义消息
    m_progressBar.SetOwner(this);
    m_progressBar.SetRange(0, 100);
}

// 自定义线程类
class CMyThread : public CWinThread
{
public:
    BOOL InitInstance() override
    {
        // 后台任务
        for (int i = 0; i <= 100; i++)
        {
            // 更新进度条
            SendMessage(m_pMainWnd->m_hWnd, WM_MY_UPDATE_PROGRESS, i, 0);

            // 模拟耗时操作
            Sleep(100);
        }

        // 任务完成
        PostMessage(m_pMainWnd->m_hWnd, WM_MY_TASK_COMPLETE, 0, 0);

        return TRUE;
    }

    void ExitInstance() override
    {
        // 释放线程对象
        delete this;
    }
};

// 主窗口消息映射
BEGIN_MESSAGE_MAP(CMyDialog, CDialog)
    ON_MESSAGE(WM_MY_UPDATE_PROGRESS, OnUpdateProgress)
    ON_MESSAGE(WM_MY_TASK_COMPLETE, OnTaskComplete)
END_MESSAGE_MAP()

// 更新进度条的消息处理函数
LRESULT CMyDialog::OnUpdateProgress(WPARAM wParam, LPARAM lParam)
{
    int progress = static_cast<int>(wParam);

    m_progressBar.SetPos(progress);

    return 0;
}

// 任务完成的消息处理函数
LRESULT CMyDialog::OnTaskComplete(WPARAM wParam, LPARAM lParam)
{
    AfxMessageBox(_T("任务完成"));

    return 0;
}

The above is a simple example of implementing a multi-threaded progress bar. In actual applications, one may also need to consider issues such as thread synchronization and exception handling.

Leave a Reply 0

Your email address will not be published. Required fields are marked *