I am looking for an efficient structure for drawing graphics to a bitmap in memory, and then drawing it to the picturebox on my WinForm. I am using a timer event so that it will draw many times a second.I will show relevant code that I have been using below:
These are defined in the beginning:
- private System.Timers.Timer mainTimer = new System.Timers.Timer();
- private double fps = 10.0;
- mainTimer.Elapsed += new System.Timers.ElapsedEventHandler(MainLoop);
- mainTimer.Interval = 1000.0 / fps;
- mainTimer.Enabled = true;
After that I have drawing code in my main loop. Note, this is just for testing at present:
- private void MainLoop()
- {
- Rectangle rectImg = new Rectangle(0, 0, picbox_width, picbox_height);
- Bitmap memImg = new Bitmap(picbox_width, picbox_height);
- memImg.SetResolution(hres, vres);
-
- using (Graphics g = Graphics.FromImage(memImg))
- {
- using(ImageAttributes wrapMode = new ImageAttributes())
- {
- wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
- g.DrawImage(backgroundImg, rectImg, 0, 0, 100, 100, GraphicsUnit.Pixel, wrapMode);
- }
- g.DrawPolygon(borderColor, polygonPoints);
- MyPictureBox.BackgroundImage = memImg;
- }
- }
One of the problems I am facing is that I get an error on line 12. The error is as follows:
Exception User-Unhandled
System.InvalidOperationException: 'Object is currently in use elsewhere.'
I have read that it is possibly an error with threading and that I need to use a BeginInvoke method to solve the problem. My main questions are do I need the BeginInvoke on each of my graphics calls, or is there a simpler format I could use (for any of my above code) to make it more straightforward and efficient?
Please note that there may be some code spelling errors, as the computer I code on is not allowed an Internect connection or to have any storage connected, so I am copying it the best I can. School rules :P