问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/19896393/updating-a-textbox-from-isamplegrabbercb