0

I have a panel that contains a active x component to show a camera stream. this is external code. this panel can only be run a STA thread becouse of the camera driver.

how can i show this panel on a form created on another thread? for example:

[STAThread]
        public Main()
        {

            Panel display = new Panel();

            Thread form = new Thread(()=>
            {
                Form displayForm = new Form();
                displayForm.Show();
                displayForm.Controls.Add(display);
            });
            form.Start();

            CameraComponent axCamera = new CameraComponent(); //create new camera component active x component
            display.Controls.Add(axCamera);
        }

But this throws an exception on : display.Controls.Add(axCamera); exception: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

Jeffnl
  • 261
  • 1
  • 4
  • 21

1 Answers1

0

You have to invoke that operation:

Thread form = new Thread(()=>
{
    Form displayForm = new Form();
    displayForm.Show();
    display.Invoke((MethodInvoker)delegate { displayForm.Controls.Add(display); });
});

and to be honest I do not see any reason why you would want to do that. It is very simple and fast operation and you should do it on UI thread instead of creating new one.

gzaxx
  • 17,312
  • 2
  • 36
  • 54
  • The code shown is a simple version of the actal code, in the actual code the user can create a camera on different forms, and all these camera panels have to be on thesame thread – Jeffnl Jun 24 '13 at 09:14
  • Ah I see, anyways my solution should work for you just fine :) – gzaxx Jun 24 '13 at 09:16
  • I ame still getting the same exception – Jeffnl Jun 24 '13 at 11:22
  • There was small bug, try again please :) – gzaxx Jun 24 '13 at 11:29
  • it seems to be working now, but antoher problem is poping up now, the exception: 'Invoke or BeginInvoke cannot be called on a control until the window handle has been created.' is now up when the invoke is trying to execute, i have checked for the handles but the handle of the display is never created on the thread where the invoke is executed from. how is this possible and how to make sure that i can acces it from all threads? – Jeffnl Jun 24 '13 at 12:17
  • If this form is without controls then it should be quick to initialize so maybe create it on owning thread? I do not know any other way how to fix it :/ – gzaxx Jun 24 '13 at 13:03