I have a problem with code optimization. My program each tick makes a screenshot of the screen and copies from it a plot for the bitmap attribute.

Graphics bmpGraphics; Bitmap bitmap; Bitmap GetScreen() { using (bmpGraphics = Graphics.FromImage(bitmap)) { rp = Form1.regionPos;//l_pos bmpGraphics.CopyFromScreen(rp.X, rp.Y, 0, 0, new Size(390, 50)); } Thread.Sleep(1); return bitmap; } 

When you run the program, the performance of the computer is almost halved. Perhaps because I initially receive images of the entire screen, and then I cut out the necessary area from it.

How can I speed up the application?

  • And how often do you call your function? - VladD
  • @VladD "every tick" ... - Sergey V
  • @dthpth: Then no wonder :-) - VladD
  • 3
    Apparently, you have a problem at a much higher level than optimization. Why do you need every tick to take a screenshot? - nitrocaster

1 answer 1

Here's the code for taking a screenshot from a piece of screen ...

 public Bitmap TakeScreenshot(Rectangle rect) { Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(bmp); g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy); return bmp; } 

But your problem is more global and it will not save you that much. Change the period between tics for a longer period at a minimum (select the optimal size)

And in general, consider whether it is really necessary. =) It may be possible to achieve the desired result without it.