0

私がやろうとしているのは、現在のフォームの特定の位置でピクセルカラーを取得することです。しかし、私がメソッドを呼び出すポイントは、別のスレッドにあります。アプリケーションを実行すると、次のエラーが発生します。

クロススレッド操作が無効です:コントロール'Form1'は、それが作成されたスレッド以外のスレッドからアクセスされました。

スレッドコード:

Thread drawThread;
drawThread = new Thread(drawBikes);

drawBikesコード:

public void drawBikes()
{
    MessageBox.Show("Bike "+bike.color.ToString()+": "+Form1.ActiveForm.GetPixelColor(bike.location.X, bike.location.Y).ToString());
}

GetPixelColorメソッド(別の静的クラス)は次のとおりです。

public static class ControlExts
{
    public static Color GetPixelColor(this Control c, int x, int y)
    {
        var screenCoords = c.PointToScreen(new Point(x, y));
        return Win32.GetPixelColor(screenCoords.X, screenCoords.Y);
    }
}

どこで呼び出しを呼び出しますか?

4

2 に答える 2

1

UIと対話している他のスレッドからInvokeを呼び出す必要があります。あなたの場合、drawBikes()はUIを更新しようとしています。これを試して:

    public void drawBikes()
    {
        if (InvokeRequired)
        {
            this.Invoke(new MethodInvoker(drawBikes));
            return;
        }
        // code below will always be on the UI thread
        MessageBox.Show("Bike "+bike.color.ToString()+": "+Form1.ActiveForm.GetPixelColor(bike.location.X, bike.location.Y).ToString());

    }
于 2012-04-13T18:30:30.087 に答える
0

コードを BeginInvoke内に配置します

何かのようなもの

            public static class ControlExts
            {
                      public static Color GetPixelColor(this Control c, int x, int y)
                      {
                         this.BeginInvoke(new Action(() =>
                          {
                          var screenCoords = c.PointToScreen(new Point(x,y));
                          return Win32.GetPixelColor(screenCoords.X, screenCoords.Y);
                         }));

                       }
           }
于 2012-04-13T18:31:20.287 に答える