Capture screenshot of active window?

前端 未结 11 2234
春和景丽
春和景丽 2020-11-21 23:34

I am making a screen capturing application and everything is going fine. All I need to do is capture the active window and take a screenshot of this active window. Does an

11条回答
  •  被撕碎了的回忆
    2020-11-22 00:27

    Here is a snippet to capture either the desktop or the active window. It has no reference to Windows Forms.

    public class ScreenCapture
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();
    
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetDesktopWindow();
    
        [StructLayout(LayoutKind.Sequential)]
        private struct Rect
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }   
    
        [DllImport("user32.dll")]
        private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);
    
        public static Image CaptureDesktop()
        {
            return CaptureWindow(GetDesktopWindow());
        }
    
        public static Bitmap CaptureActiveWindow()
        {
            return CaptureWindow(GetForegroundWindow());
        }
    
        public static Bitmap CaptureWindow(IntPtr handle)
        {
            var rect = new Rect();
            GetWindowRect(handle, ref rect);
            var bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
            var result = new Bitmap(bounds.Width, bounds.Height);
    
            using (var graphics = Graphics.FromImage(result))
            {
                graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
            }
    
            return result;
        }
    }
    

    How to capture the whole screen:

    var image = ScreenCapture.CaptureDesktop();
    image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg);
    

    How to capture the active window:

    var image = ScreenCapture.CaptureActiveWindow();
    image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg);
    

    Originally found here: http://www.snippetsource.net/Snippet/158/capture-screenshot-in-c

提交回复
热议问题