0

What i'm trying to do is to get a pixel color at a certain position on the current form. But, the point at which I call the method is in a seperate thread. When I run the application, I get an error:

Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.

Thread Code:

Thread drawThread;
drawThread = new Thread(drawBikes);

drawBikes Code:

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

Here is the GetPixelColor Method (in a separate static class):

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);
    }
}

Where do I call the Invoke?

Ian McCullough
  • 1,423
  • 4
  • 25
  • 36
  • 1
    Dublicate of millions of questions http://stackoverflow.com/questions/22356/cleanest-way-to-invoke-cross-thread-events – L.B Apr 13 '12 at 18:26
  • @ L.B doubt on reported count of questions, but.. :) – Tigran Apr 13 '12 at 18:46

2 Answers2

1

You need to call Invoke from any other thread that is interacting with the UI. In your case, drawBikes() is trying to update the UI. Try this:

    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());

    }
Steve Wong
  • 2,038
  • 16
  • 23
0

Put your code inside BeginInvoke

Something like

            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);
                         }));

                       }
           }
Emmanuel N
  • 7,350
  • 2
  • 26
  • 36