Ian McCullough
Ian McCullough

Reputation: 1443

Invoke in static multithreading instance

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?

Upvotes: 0

Views: 171

Answers (2)

Emmanuel N
Emmanuel N

Reputation: 7449

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

                       }
           }

Upvotes: 0

Steve Wong
Steve Wong

Reputation: 2256

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

    }

Upvotes: 1

Related Questions