0

I currently have a working program which displays a preview from my webcam and uses the ISampleGrabberCB interface.

Using the SampleCB my program converts the image to a bitmap and then processes the image for a barcode which is then decoded. This works perfectly when I show the result using a MessageBox however when I wish to edit a textbox on my main form with this result I get a few errors when I start my program.

I am trying to update my text box using the following code within the ISampleGrabberCB interface:

public int SampleCB(double sampletime, IMediaSample sample)
    {
        if (sample == null)
        {
            return -1;
        }
        try
        {
            int length = sample.GetActualDataLength();
            IntPtr buffer;
            BitmapData bitmapData = new BitmapData();

            Form1 f1 = new Form1("", "", "");


            if (sample.GetPointer(out buffer) == 0 && length > 0)
            {
                Bitmap bitmapOfFrame = new Bitmap(width, height, pitch, PixelFormat.Format24bppRgb, buffer);


            }

The method changeTextBox1 is in my main form and is as follows:

public void changeTextBox1(string text)
    {
        textBox1.Text = text;
    }

The errors I get are firstly A device attached to the system in not functioning properly and then no such supported interface. This seems to only happen when I use the Form1 f1 = new Form1("","",""); line.

So as I said if i remove the line Form1 f1 = new Form1("","",""); and replace changeTextBox1(result.Text); with MessageBox.Show(result.Text.ToString()); this works.

How would I go about updating the textbox instead of using a MessageBox?

legohead
  • 530
  • 2
  • 8
  • 23

1 Answers1

2

You should make UI changes in the main UI thread, however your callback SampleCB is getting called from another system thread, hence the errors. Use message posting or other ways to safely pass data from callback's thread to main UI thread and update UI with new data in the main UI thread.

Dee Mon
  • 1,016
  • 6
  • 7
  • How would I use invoking to do this? i've looked around at a few of the SO questions but I do not see what I am supposed to be doing? – legohead Nov 11 '13 at 10:23
  • You need to post a window message to your UI thread, or otherwise synchronize execution, e.g. using a queue you add to in callback thread, and you remove from in UI thread. – Roman R. Nov 19 '13 at 20:13