4

例外はコードにあります:

private void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
   ActiveDownloadJob adJob = e.UserState as ActiveDownloadJob;
   if (adJob != null && adJob.ProgressBar != null)
   {
      adJob.ProgressBar.Invoke((Action)(() => adJob.ProgressBar.Value = e.ProgressPercentage));
   }
}

行上:

adJob.ProgressBar.Invoke((Action)(() => adJob.ProgressBar.Value = e.ProgressPercentage));

これは form1 の ActiveDownloadJob クラスです。

class ActiveDownloadJob
{
            public DownloadImages.DownloadData DownloadData;
            public ProgressBar ProgressBar;
            public WebClient WebClient;

            public ActiveDownloadJob(DownloadImages.DownloadData downloadData, ProgressBar progressBar, WebClient webClient)
            {
                try
                {
                    this.DownloadData = downloadData;
                    this.ProgressBar = progressBar;
                    this.WebClient = webClient;
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.ToString());
                }
            }
        }

現在は backgroundworker を使用していないため、この行を呼び出す必要があるかどうかはわかりませんが、わかりません。

これは完全な例外メッセージです。ウィンドウ ハンドルが作成されるまで、Invoke または BeginInvoke をコントロールで呼び出すことはできません。

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
       at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
       at System.Windows.Forms.Control.Invoke(Delegate method)
       at WeatherMaps.Form1.DownloadProgressCallback(Object sender, DownloadProgressChangedEventArgs e) in d:\C-Sharp\WeatherMaps\WeatherMaps\WeatherMaps\Form1.cs:line 290
       at System.Net.WebClient.OnDownloadProgressChanged(DownloadProgressChangedEventArgs e)
       at System.Net.WebClient.ReportDownloadProgressChanged(Object arg)
  InnerException: 

Invoke を使用せずにこの行を変更するにはどうすればよいですか、または Invoke が必要な場合、行と例外を修正するにはどうすればよいですか?

Form1 フォームの終了イベントで処理する必要があることはわかっていますが、どうすればよいですか? form1 フォームの終了イベントで何をすればよいですか?

4

3 に答える 3

3

問題は、ウィンドウ ハンドルを持つ前にプログレス バーを変更しようとしていることです。それを解決する1つの方法は次のとおりです。

if (adJob.ProgressBar.Handle != IntPtr.Zero)
{
    adJob.ProgressBar.Invoke((Action)(() =>
        adJob.ProgressBar.Value = e.ProgressPercentage));
}

Formこれは、が実際に表示される前にこのメソッドを呼び出していることが原因である可能性があります。

于 2013-11-13T15:54:19.460 に答える
-1

それを試してみてください:

MethodInvoker mi = () => adJob.ProgressBar.Value = e.ProgressPercentage;
if(InvokeRequired) BeginInvoke(mi);
else mi();
于 2013-11-13T15:49:14.343 に答える