Implementing a "Continuous Capture" with single image snaps - c#

I have some code below that can take the current Image and displaying it whenever I click a PushSnap Button. How can I go about having it continuously capturing and displaying the updated image in an interval (say 100 ms)
private void PushSnap_Click(object sender, EventArgs e)
{
if (mycam == null)
{
MessageBox.Show("Internal Error: mycam is null");
return; // internal error
}
string text = "";
if (IsMyFormStatus_Opened())
{
if (!mydcam.buf_alloc(3))
{
MessageBox.Show("Frame allocation failed");
return;
}
}
// start acquisition
mycam.m_capmode = CAMCAP_START.SNAP; //one time capturing where Acquisition will start after m_nFrameCount frames
if (!mycam.cap_start())
{
return;
}
MyFormStatus_Acquiring();
MyThreadCapture_Start();
}
The Following MyThreadCapture_Start()
private void MyThreadCapture_Start()
{
m_threadCapture = new Thread(new ThreadStart(OnThreadCapture));
m_threadCapture.IsBackground = true;
m_threadCapture.Start();
}
and the following OnThreadCapture()
private void OnThreadCapture()
{
using (mycamwait = new MycamWait())
{
while (True)
{
CAMWAIT eventmask = CAMWAIT.CAPEVENT.FRAMEREADY | CAMWAIT.CAPEVENT.STOPPED;
DCAMWAIT eventhappened = DCAMWAIT.NONE;
if (mycamwait.start(eventmask, ref eventhappened))
{
if (eventhappened & CAMWAIT.CAPEVENT.FRAMEREADY)
{
int NewestFrame = 0;
int FrameCount = 0;
if (mycam.cap_transferinfo(ref NewestFrame, ref FrameCount))
{
MyUpdateImage(iNewestFrame);
}
}
if (eventhappened & CAMWAIT.CAPEVENT.STOPPED)
{
bContinue = false;
if (m_cap_stopping == false && mycam.m_capmode == CAMCAP_START.SNAP)
{
//cap_stop() happens automatically, therefore update the main dialog
//MySnapCaptureFinished();
}
}
}
}
}
Afterwards the Display is updated in the following way
private void UpdateDisplay()
{
Image oldImg = PicDisplay.Image;
if (m_bitmap != null)
{
// Show center of image
Int32 y0 = (m_image.height - PicDisplay.Height) / 2;
Int32 x0 = (m_image.width - PicDisplay.Width) / 2;
Rectangle rc = new Rectangle(x0, y0, PicDisplay.Width, PicDisplay.Height);
Bitmap bmp = new Bitmap(PicDisplay.Width, PicDisplay.Height, PixelFormat.Format24bppRgb);
using (var gr = Graphics.FromImage(bmp))
{
gr.DrawImage(m_bitmap, 0, 0, rc, GraphicsUnit.Pixel);
}
PicDisplay.Image = bmp;
PicDisplay.Refresh();
}
else
{
PicDisplay.Image = null;
}
if (oldImg != null)
oldImg.Dispose();
}

I would really recommend using Tasks instead of Threads. That should let you update your methods to take parameters and return results:
Image CaptureImage(); // I.e. similar code to OnThreadCapture
UpdateDisplay(Image);
And capture an image like:
public async void PushSnap_Click(){
...
try{
var image = await Task.Run(CaptureImage);
DisplayImage(image);
}
catch{
// Handle exceptions
}
That should let you simply rewrite your capture code to use a loop if you want live capture:
while(showLiveImagesBool){
var image = await Task.Run(CaptureImage);
DisplayImage(image);
}
The await-part should ensure the UI thread is not blocked while waiting for an image to be captured. If you do not want to show every image you might use a timer instead of a loop, just pick a timer that runs on the UI thread.
Keep in mind that showing live images will require a bit more performance, so you might need to optimize display and/or capture code. Ideally you should reuse image buffers when doing the capturing and displaying, otherwise you will allocate a fair amount of large objects that require a 2 gen GC to clean up.

Related

Saving a bitmap from a variable gives "invalid parameter"

I need to save an image to disk that came from a web-cam between 5 and 10 seconds ago from when the "save" command comes in via serial port.
To get there, I have the webcam going into a pictureBox.Image (using opencv4), and then 2 Bitmap variables. Every 5 seconds a timer ticks, and Stored_bitmap_2 = Stored_bitmap_1, then Stored_bitmap_1 = (bitmap) pictureBox.Image.
When the right serial command comes in, I try to
Stored_image_2.Save("C:\Users\GreenWorld\Desktop\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
and I get a run-time error of invalid parameter.
When I do the same thing in a stand-alone project with some buttons (inside the button-click event handler), it works every time.
When I do this inside the serialPort_DataReceived handler, I get all kinds of cross-thread errors. So, I moved the save attempt to its own subroutine, and that fixed that but now this.
I am by no means a professional programmer, I'm an engineer with a simple problem and I can usually write a little simplistic code to fix my immediate issue. Please go easy on me in the explanation :-)
Sample code:
using OpenCvSharp;
using OpenCvSharp.Extensions;
namespace Weld_picture
{
public partial class Form1 : Form
{
// Create class-level accessible variables
int Welding_camera_ID = 1;
VideoCapture capture;
Mat frame;
Bitmap image;
private Thread camera;
bool isCameraRunning = false;
string Serial_command = "";
Bitmap Stored_image_1;
Bitmap Stored_image_2;
bool Image_saved = false;
string Station_ID = "GWM-PWS-01";
string File_name = "";
private void CaptureCamera() // from someone else's sample code
{
camera = new Thread(new ThreadStart(CaptureCameraCallback));
camera.Start();
}
private void CaptureCameraCallback() // from someone else's sample code
{
frame = new Mat();
capture = new VideoCapture(Welding_camera_ID);
capture.Open(Welding_camera_ID);
if (capture.IsOpened())
{
while (isCameraRunning)
{
capture.Read(frame);
image = BitmapConverter.ToBitmap(frame);
if (pictureBox1.Image != null)
{
pictureBox1.Image.Dispose();
}
pictureBox1.Image = image;
}
}
}
public Form1()
{
InitializeComponent();
SerialPort1.Open();
}
private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string dummy;
char CR = (char)0x0D;
while (SerialPort1.BytesToRead > 0)
{
Serial_command += (char)SerialPort1.ReadByte();
}
while (Serial_command.IndexOf(CR) > 0)
{
dummy = Serial_command.Substring(0, Serial_command.IndexOf(CR));
Serial_command = Serial_command.Substring(Serial_command.IndexOf(CR) + 1, (Serial_command.Length - (Serial_command.IndexOf(CR) + 1)));
Serial_command.Trim();
dummy.Trim();
proc_Process_serial_data(dummy);
}
}
//*************************************************************************************************************************************
/* the first timer is a 5-second interval. It's the "memory" function so that if/when the save-to-disk is triggered I can store the last-time-shutter-open image */
//*************************************************************************************************************************************
private void Timer_picture_interval_Tick(object sender, EventArgs e)
{
checkBox1.Checked = !checkBox1.Checked;
Timer_picture_interval.Stop();
Stored_image_2 = Stored_image_1;
Stored_image_1 = (Bitmap) pictureBox1.Image;
Timer_picture_interval.Start();
}
//*************************************************************************************************************************************
// the second timer is a 30-second interval. It's the way to turn capture off if the PLC/camera box somehow goes off-line
//*************************************************************************************************************************************
private void Timer_camera_powerdown_Tick(object sender, EventArgs e)
{
if (isCameraRunning)
capture.Release();
isCameraRunning = false;
Timer_picture_interval.Stop();
}
//*************************************************************************************************************************************
private void proc_Process_serial_data(string Serial_string)
{
if (Serial_string.IndexOf("Still here") > 0)
{
if (!isCameraRunning)
CaptureCamera();
isCameraRunning = true;
}
if (Serial_string.IndexOf("Sun's up") > 0)
{
Timer_picture_interval.Start();
Timer_camera_powerdown.Start();
}
if (Serial_string.IndexOf("It's dark") > 0)
{
if ((Stored_image_2 != null) && (!Image_saved)) // in case there's 2 subsequent requests to save the same thing (weld stutter)
{
File_name = "C:\\Users\\GreenWorld\\Desktop\\" + Station_ID + " D" + DateTime.Now.ToString("yyyy_MM_dd THH_mm_ss") + ".jpg";
Stored_image_2.Image.Save("C:\\Users\\GreenWorld\\Desktop\\test.bmp" , System.Drawing.Imaging.ImageFormat.Bmp );
Image_saved = true;
Timer_picture_interval.Stop();
}
Timer_camera_powerdown.Start();
}
}
}
}
You likely be able to fix the cros-threading error by simply calling your proc_Process_serial_data() method within an Invoke() call.
Change:
proc_Process_serial_data(dummy);
To:
this.Invoke((MethodInvoker)delegate ()
{
proc_Process_serial_data(dummy);
});
Also, these two lines aren't actually doing anything:
Serial_command.Trim();
dummy.Trim();
To Trim() the strings, you have capture the returned strings and re-assign them to the original variables:
Serial_command = Serial_command.Trim();
dummy = dummy.Trim();

Real Time chart performance issue c# winform

I am currently using liveChart to plot a real time graph of 3 values: a position, a load and a deformation. The program is based on the Doli.DoPE library (a proprietary dll)
In MainForm.cs, there is an event that is triggered everytime the sensor records a new value (every millisecond or so).
public void Initialisation()
{
//...
MyEdc.Eh.OnDataHdlr += new DoPE.OnDataHdlr(OnData)
//...
}
with
private int OnData(ref DoPE.OnData Data, object Parameter)
{
DoPE.Data Sample = Data.Data;
if (Data.DoPError == DoPE.ERR.NOERROR)
{
Int32 Time = Environment.TickCount;
if ((Time - LastTime) >= 250 /*ms*/)
{
// Send the data from the ondata handler inside of a global list
ListData.time.Add(Sample.Time);
ListData.position.Add(Sample.Sensor[(int)DoPE.SENSOR.SENSOR_S]);
ListData.load.Add(Sample.Sensor[(int)DoPE.SENSOR.SENSOR_F]);
ListData.extend.Add(Sample.Sensor[(int)DoPE.SENSOR.SENSOR_E]);
Thread ThForUpdateChart = new Thread(() =>
{
if (NewINstanceOfChart != null)
{ NewINstanceOfChart.UpdateValues(ListData.time.Last(), ListData.position.Last(),ListData.load.Last(), ListData.extend.Last()); }
});
ThForUpdateChart.Start();
LastTime = Time;
}
}
return 0;
}
The function UpdateValues is part of a second form RealTimeChart.cs called in the MainForm through a button click event:
private void btnGraph_Click(object sender, EventArgs e)
{
var thread = new Thread(() =>
{
NewINstanceOfChart = new RealTimeChart(ListData);
NewINstanceOfChart.Show();
});
thread.Start();
}
the form RealTimeCharts.cs is initalised this way:
public RealTimeChart(Globals ListData)
{
InitializeComponent();
//measures = ListData;
ListPosition = new ChartValues<ObservablePoint>();
for (int i = 0; i < measures.load.Count(); i++)
{
ListPosition.Add(new ObservablePoint
{
X = measures.time[i],
Y = measures.position[i]
});
}
ListLoad = new ChartValues<ObservablePoint>();
for (int i = 0; i < measures.load.Count(); i++)
{
ListLoad.Add(new ObservablePoint
{
X = measures.time[i],
Y = measures.load[i]
});
}
ListExtend = new ChartValues<ObservablePoint>();
for (int i = 0; i < measures.load.Count(); i++)
{
ListExtend.Add(new ObservablePoint
{
X = measures.time[i],
Y = measures.extend[i]
});
}
resultChart.Series.Add(new LineSeries
{
LineSmoothness = 0,
Values = ListPosition,
PointGeometrySize = 2,
StrokeThickness = 4
});
SetXAxisLimits();
}
And the UpdateValues function is defined as followed:
public void UpdateValues(double time, double position, double load, double extend)
{
measures.time.Add(time-measures.TareTime);
measures.position.Add(position);
measures.load.Add(load);
measures.extend.Add(extend);
UpdateEnabledSequencialPartToTrue();
}
public void UpdateEnabledSequencialPartToTrue()
{
if (this.InvokeRequired)
BeginInvoke(new System.Action(() => this.InternalUpdateEnabledSequencialPartToTrue()));
else
InternalUpdateEnabledSequencialPartToTrue();
}
private void InternalUpdateEnabledSequencialPartToTrue()
{
try
{
ListPosition.Add(new ObservablePoint
{
X = measures.time.Last(),
Y = measures.position.Last()
});
ListLoad.Add(new ObservablePoint
{
X = measures.time.Last(),
Y = measures.load.Last()
});
ListExtend.Add(new ObservablePoint
{
X = measures.time.Last(),
Y = measures.extend.Last()
});
//LineSeries plot = new LineSeries();
SetXAxisLimits();
// lets only use the last 14400 values (1h long recording, 14400 values at frequency of 1 record very 250ms, see OnData function MainForm
if (measures.time.Count > 14400)
{
ListPosition.RemoveAt(0);
ListLoad.RemoveAt(0);
ListExtend.RemoveAt(0);
}
}
catch (NullReferenceException) { }
}
After a minute, the programme starts to be really laggy. I tried putting the second winform (RealTimeCharts) on another thread so the MainForm does not lag (it is piloting a machine, it has to be responsive), but no success.
I would like to know if the whole thing is laggy because the code is way too bad, or if it is liveChart that reached its (free) limits. Would you advice another way to plot real time data ?
In MainForm.cs, there is an event that is triggered everytime the sensor records a new value (every millisecond or so).
That is natturally way higher then what Winforms Drawing can take. See, drawing a GUI is expensive. If you only do it once per user-triggered event, you will never notice that. But do it from a loop - including sampling a sensor every MS - and you can quickly overlord the UI. My first Multithreading tests actually appeared to have failed on big numbers, becaus I ended up sending so many updates I plain overloaded the GUI thread. Since then I know not to go past progress bars.
You can add data to a background collection as quickly as you can sample them, but you can not draw that quickly. And honestly drawing more often then 30-60 times/second (every ~17 ms) is not really going to help anyone anyway. Usually you can not use a timer, as the Tick might happen more often then it can be processed - again, a GUI Thread with a overflowing Event Queue.
I do not have any rate limiting code for WindowsForms. But I would guess an Event that re-queues itself at the end of the EventQueue after finishing the work would work.

Unfocus live-updating chart

I have a project which consists of two forms, MainForm and CrossCorrPlotForm. On CrossCorrPlotForm, I have two charts (CrossCorrExpChart and CrossCorrRefChart) which I enabled scroll wheel zooming on, using the code described here and here.
Everything was working perfectly fine, until I added another chart (histChart), on MainForm, which is updated on each frame incoming from a camera (15-20 FPS), using a BackgroundWorker to collect and plot the data from the images. Now, both my charts on CrossCorrPlotChart are not zoomable anymore.
I presume this has something to do with the live-updating chart taking back the focus on each update. I tried adding histChart.Focus = false in the code but to no avail, as it seems "Control.Focused is read-only".
Does anyone have an idea how to make my charts zoomable again ?
Thanks
EDIT : Here is the code for the BackgroundWorker that updates chartHist :
private void OnFrameReceived(Frame frame)
{
bgw1.RunWorkerAsync(frame);
}
private void bgw1_DoWork(object s, DoWorkEventArgs e)
{
Frame frame = (Frame)e.Argument;
myBitmap = null;
try
{
frame.Fill(ref myBitmap);
mycamera.QueueFrame(frame);
SaveBitmap = myBitmap.Clone(cloneRect, myBitmap.PixelFormat);
BitmapToPrint = myBitmap.Clone(cloneRect, myBitmap.PixelFormat);
}
catch {}
}
private void bgw1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (this.InvokeRequired)
{
BeginInvoke((Action)(() => bgw1_RunWorkerCompleted(sender, e)));
}
else
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
DataFromBitmap DataFromBitmapHist = new DataFromBitmap(SaveBitmap.Clone(cloneRect, SaveBitmap.PixelFormat));
PixelColorCount = DataFromBitmapHist.ColorCountOutput();
}).Start();
chartHist.Titles["Title2"].Visible = false;
chartHist.Series["Pixel count"].Points.Clear();
//Plotting the pixel counter, to detect saturation
for (int i = 0; i < PixelColorCount.Length; i++)
{
chartHist.Series["Pixel count"].Points.AddXY(i, PixelColorCount[i]);
}
//If there are saturated pixels : toggle a title on chartHist to warn the user
if (PixelColorCount.Last() > 1)
{
chartHist.Titles["Title1"].Visible = false;
chartHist.Titles["Title2"].Visible = true;
}
else
{
chartHist.Titles["Title1"].Visible = true;
chartHist.Titles["Title2"].Visible = false;
}
}
}
NOTES :
OnFrameReceived is a function from the API of the camera, it contains code that fires when a Frame is received from the camera.
frame.Fill puts the image contained in the Frame object in a Bitmap.
mycamera.QueueFrame sends back the Frame object to the camera, to receive a new image.
I had to use multiple threads, because using the UI thread too much resulted in blocking the reception from the camera.

C# .NET 4.0 Drag and drop between two applications

So I'd really like to drag and drop data between two instances of an application; however, if there is data present at the target point where I am dropping, I would like to swap that data with what is being dropped.
I'm trying to use a MemoryMappedFIle, and that seems to work most of the time, but it's not perfect. For example, if I do the drag / drop too quickly, the target data is simply overwritten (I assume it's not being written to the MemoryMappedFile quickly enough). Does anyone have any recommendations?
This is what I currently have:
private void pbSprite_MouseDown(object sender, MouseEventArgs e)
{
PictureBox pb = (PictureBox)(sender);
DataObject data = new DataObject();
if (pb.Name == pbSprite.Name)
{
data = new DataObject(DataFormats.Serializable, frmpkm);
}
else
{
data = new DataObject(DataFormats.Serializable, frmpkm2);
}
pb.DoDragDrop(data, DragDropEffects.Move);
MemoryMappedFile MemoryMapped = MemoryMappedFile.CreateOrOpen("name", 1000, MemoryMappedFileAccess.ReadWrite);
using (MemoryMappedViewAccessor FileMap = MemoryMapped.CreateViewAccessor())
{
PKMDS.Pokemon otherpkm = new PKMDS.Pokemon();
for (int i = 0; i < Marshal.SizeOf(otherpkm); i++)
{
FileMap.Read<byte>(i, out otherpkm.Data[i]);
}
if (pb.Name == pbSprite.Name)
{
frmpkm.Data = otherpkm.Data;
}
else
{
frmpkm2.Data = otherpkm.Data;
}
lblData.Text = frmpkm.SpeciesName;
lblData2.Text = frmpkm2.SpeciesName;
pbSprite.Image = frmpkm.Sprite;
pbSprite2.Image = frmpkm2.Sprite;
}
}
private void pbSprite_DragDrop(object sender, DragEventArgs e)
{
if (e.Data != null)
{
PictureBox pb = (PictureBox)(sender);
PKMDS.Pokemon otherpkm = (PKMDS.Pokemon)e.Data.GetData(DataFormats.Serializable);
MemoryMappedFile MemoryMapped = MemoryMappedFile.CreateOrOpen("name", 1000, MemoryMappedFileAccess.ReadWrite);
using (MemoryMappedViewAccessor FileMap = MemoryMapped.CreateViewAccessor())
{
for (int i = 0; i < Marshal.SizeOf(frmpkm); i++)
{
if (pb.Name == pbSprite.Name)
{
FileMap.Write<byte>(i, ref frmpkm.Data[i]);
}
else
{
FileMap.Write<byte>(i, ref frmpkm2.Data[i]);
}
}
}
if (pb.Name == pbSprite.Name)
{
frmpkm.Data = otherpkm.Data;
}
else
{
frmpkm2.Data = otherpkm.Data;
}
lblData.Text = frmpkm.SpeciesName;
lblData2.Text = frmpkm2.SpeciesName;
pbSprite.Image = frmpkm.Sprite;
pbSprite2.Image = frmpkm2.Sprite;
}
}
Two possible things to try
Move the call to pb.DoDragDrop(data, DragDropEffects.Move); after the creation of the memory mapped file. This will cause a delay in the start of the drag/drop action but should ensure that the data has been written to the file.
The other alternative is to write the data to the mmf in a separate thread and have it set and Event when the data is written. Then pbSprite_DragDrop can wait for the event to be signaled before reading from the file.

Calling a function in another thread C#

I don't know how to put this but I'll try my best.
I have a Windows form application which uses a webcam to take a photo of a user which works fine, I'm using the directshownet library found here http://directshownet.sourceforge.net/ and have used the DxSnap sample to take the photo.
The next part of the application uses an RFID tag reader that once a tag is scanned, it calls the take photo method. And this is where the problem is coming in, because the RFID listen method is run in a separate thread to the GUI thread, because it is an infinite while loop.
The class that is used to take the picture takes an instance of a picturebox control as a parameter for it's constructor, which is created in the main thread, and i think this is where the problem is.
Each part of the application works fine separately but when i try to call the method to take the photo from the listener thread all hell breaks loose and the app crashes.
Does anybody know how I could call a method of the object that is initialized in the main thread (that takes the photo) from the listener thread?
I've tried delegate and invoke, but can't figure it out as i don't want to manipulate the control directly, but rather let the object do it in the main thread.
Here's some code:
private Capture cam;
private int portIndex = -1;
private ArrayList AlreadyOpenPortList = new ArrayList();
private byte readerAddr = 0;
private Thread listenThread;
IntPtr m_ip = IntPtr.Zero;
public podiumForm()
{
InitializeComponent();
// scanner and camera startup
startCam();
openComs();
openRF();
startListening();
}
private void startListening()
{
listenThread = new Thread(new ThreadStart(this.Listen));
listenThread.Start();
}
/// <summary>
/// Method of retrieving code tag details from reader
/// </summary>
private void Listen()
{
int fCmdRet = 0x30;
byte state = 1;
byte AFI = 00;
byte[] DSFIDAndUID = new byte[9];
byte cardNumber = 0;
string strDSFIDAndUID = "";
byte outputSet;
if (!GetCurrentUsePort())
{
MessageBox.Show("Open ComPort, Please");
return;
}
while (true)
{
fCmdRet = StaticClassReaderA.Inventory(ref readerAddr, ref state, ref AFI, DSFIDAndUID, ref cardNumber, portIndex);
if (fCmdRet == 0)
{
outputSet = 0;
fCmdRet = StaticClassReaderA.SetGeneralOutput(ref readerAddr, ref outputSet, portIndex);
strDSFIDAndUID = ByteArrayToHexString(DSFIDAndUID).Replace(" ", "");
outputSet = 3;
fCmdRet = StaticClassReaderA.SetGeneralOutput(ref readerAddr, ref outputSet, portIndex);
SavePic(strDSFIDAndUID.Substring(2, 16));
//MessageBox.Show(strDSFIDAndUID.Substring(2, 16));
//ShutDown();
}
}
}
private void SavePic(string text)
{
Cursor.Current = Cursors.WaitCursor;
// Release any previous buffer
if (m_ip != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(m_ip);
m_ip = IntPtr.Zero;
}
// here's where it crashes
// capture image
m_ip = cam.Click();
Bitmap b = new Bitmap(cam.Width, cam.Height, cam.Stride, PixelFormat.Format24bppRgb, m_ip);
cam.Dispose();
// If the image is upsidedown
b.RotateFlip(RotateFlipType.RotateNoneFlipY);
pbPic.Image = b;
Cursor.Current = Cursors.Default;
MessageBox.Show("Here " + text);
}
private void startCam()
{
const int VIDEODEVICE = 0; // zero based index of video capture device to use
const int VIDEOWIDTH = 640; // Depends on video device caps
const int VIDEOHEIGHT = 480; // Depends on video device caps
const int VIDEOBITSPERPIXEL = 24; // BitsPerPixel values determined by device
cam = new Capture(VIDEODEVICE, VIDEOWIDTH, VIDEOHEIGHT, VIDEOBITSPERPIXEL, pbPic);
}
// method in capture class
public IntPtr Click()
{
int hr;
// get ready to wait for new image
m_PictureReady.Reset();
m_ipBuffer = Marshal.AllocCoTaskMem(Math.Abs(m_stride) * m_videoHeight);
try
{
m_WantOne = true;
// If we are using a still pin, ask for a picture
if (m_VidControl != null)
{
// CRASHES HERE with : System.InvalidCastException was unhandled
// Tell the camera to send an image
hr = m_VidControl.SetMode(m_pinStill, VideoControlFlags.Trigger);
DsError.ThrowExceptionForHR(hr);
}
// Start waiting
if (!m_PictureReady.WaitOne(9000, false))
{
throw new Exception("Timeout waiting to get picture");
}
}
catch
{
Marshal.FreeCoTaskMem(m_ipBuffer);
m_ipBuffer = IntPtr.Zero;
throw;
}
// Got one
return m_ipBuffer;
}
Take a look at the SynchronizationContext class; it allows you to dispatch work back on the main (UI) thread in a manner that is agnostic of how that mechanism actually works (and therefore works with WinForms and WPF). Therefore you don't need to have a reference to a Control to call Invoke on.
It is what BackgroundWorker uses behind the scenes (you may also be able to use BackgroundWorker, depending on what you're trying to do, which is slightly easier to work with).
Image image = (Image)pictureBox.Invoke ((Func<Image>) delegate { return pictureBox.Image; });

Categories

Resources