Guest User

Guest User

  • Tech Writer
  • 48
  • 11.1k

Need basic structure for loop drawing in picturebox.

Jul 18 2019 3:11 PM
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: 
 
  1. private System.Timers.Timer mainTimer = new System.Timers.Timer();  
  2. private double fps = 10.0;  
  3. mainTimer.Elapsed += new System.Timers.ElapsedEventHandler(MainLoop);  
  4. mainTimer.Interval = 1000.0 / fps;  
  5. mainTimer.Enabled = true;  
 
After that I have drawing code in my main loop. Note, this is just for testing at present:
 
  1. private void MainLoop()  
  2. {  
  3.   Rectangle rectImg = new Rectangle(0, 0, picbox_width, picbox_height);   
  4.   Bitmap memImg = new Bitmap(picbox_width, picbox_height);  
  5.   memImg.SetResolution(hres, vres);  // Resolution values from backgroundImg  
  6.    
  7.   using (Graphics g = Graphics.FromImage(memImg))  
  8.   {  
  9.     using(ImageAttributes wrapMode = new ImageAttributes())  
  10.     {  
  11.       wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);   
  12.       g.DrawImage(backgroundImg, rectImg, 0, 0, 100, 100, GraphicsUnit.Pixel, wrapMode);   
  13.     }  
  14.     g.DrawPolygon(borderColor, polygonPoints); // Parameters defined elsewhere.   
  15.     MyPictureBox.BackgroundImage = memImg;  
  16.   }   
  17. }   
 
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
 

Answers (2)