0

我想要做的是在当前表单的某个位置获取像素颜色。但是,我调用该方法的点是在一个单独的线程中。当我运行应用程序时,我收到一个错误:

跨线程操作无效:控件“Form1”从创建它的线程以外的线程访问。

线程代码:

Thread drawThread;
drawThread = new Thread(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 回答