Copy Screen Object to Bitmap File

This is not a big deal, but it is worth to share for everyone.

 1        private void copyScreen(string filename)
 2        {
 3            Bitmap bmp = new Bitmap(this.Width, this.Height);
 4            Graphics gBmp = Graphics.FromImage(bmp);
 5            IntPtr gBmpHdc = gBmp.GetHdc();
 6            IntPtr srcHdc = Win32Api.GetWindowDC(this.Handle);
 7            Win32Api.BitBlt(gBmpHdc, 00this.Width, this.Height,
 8                       srcHdc, 00,
 9                       Win32Api.SRCCOPY);
10            Win32Api.ReleaseDC(this.Handle, srcHdc);
11
12            bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Bmp);
13
14            gBmp.ReleaseHdc(gBmpHdc);
15
16            gBmp.Dispose();
17
18            bmp.Dispose();
19
20        }

21


I have tried to check the memory leak by using the below method.

 1        private void testForMemoryLeak()
 2        {
 3            int iteration = 0;
 4            bool stop = false;
 5            while (!stop)
 6            {
 7                try
 8                {
 9                    copyScreen(GlobalConfig.RootDirectory + @"\testmemleak.jpg");
10                    iteration++;
11                    iteration = iteration % 10000;
12                }

13                catch (OutOfMemoryException ome)
14                {
15                    MessageBox.Show(ome.Message+"--"+iteration.ToString());
16                    stop = true;
17                }

18                System.Threading.Thread.Sleep(10);
19            }

20        }

21

In addition, there is a VM limitation for program to run on Window Mobile 6.0. The maximum size of virtual memory is 32M. But Windows CE 6.0 has removed this limitation. That's why we often met the OutOfMemoryException although there are still memory available.
So if your program needs more memory, you need to optimize your code.

posted on 2008-03-03 11:51  Hill Jing  阅读(2097)  评论(8编辑  收藏  举报

导航