簡體   English   中英

使用backgroundWorker創建並顯示progressBar-VS2013

[英]Create and show progressBar with backgroundWorker - VS2013

我想在應用程序的另一個線程中顯示選取框進度欄。 這是我的代碼:

bkgWorker->RunWorkerAsync();

private: System::Windows::Forms::ProgressBar^  progressBar;

private: System::Void bkgWorker_DoWork(System::Object^  sender, System::ComponentModel::DoWorkEventArgs^  e) {
    progressBar = (gcnew System::Windows::Forms::ProgressBar());
    progressBar->Location = System::Drawing::Point(548, 349);
    progressBar->MarqueeAnimationSpeed = 15;
    progressBar->Name = L"progressBar";
    progressBar->Size = System::Drawing::Size(100, 23);
    progressBar->Style = System::Windows::Forms::ProgressBarStyle::Marquee;
    progressBar->TabIndex = 23;
    progressBar->Show();
}

private: System::Void bkgWorker_RunWorkerCompleted(System::Object^  sender, System::ComponentModel::RunWorkerCompletedEventArgs^  e) {
    progressBar->Hide();
}

沒有錯,但是我在窗體上看不到進度欄。 我究竟做錯了什么 ? 感謝幫助。

有更好,更新的解決方案取代了舊的優秀后台工作者。 我建議您看一下async await設計。 閱讀這篇文章: 從異步任務報告進度

代碼應如下所示:

public async void StartProcessingButton_Click(object sender, EventArgs e)
{
  // The Progress<T> constructor captures our UI context,
  //  so the lambda will be run on the UI thread.
  var progress = new Progress<int>(percent =>
  {
    textBox1.Text = percent + "%";
  });

  // DoProcessing is run on the thread pool.
  await Task.Run(() => DoProcessing(progress));
  textBox1.Text = "Done!";
}

public void DoProcessing(IProgress<int> progress)
{
  for (int i = 0; i != 100; ++i)
  {
    Thread.Sleep(100); // CPU-bound work
    if (progress != null)
      progress.Report(i);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM