Click here to Skip to main content
15,901,373 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Actually, I am using white automation framework and there is requirement to take screenshot and compare image but I am facing problem in taking screenshot. While taking screenshots multiple time of same window size of image varying. Please, let me know any solution to take screenshot of active window with fixed size. It shouldn't vary if taking screenshot of same window multiple time.
My code is this...
C#
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;
    }
}

Thanks!
Posted
Updated 27-Oct-15 1:47am
v2
Comments
Milkdog 27-Oct-15 13:55pm    
Is it the file size (xxx bytes) or image dimensions (600 x 800) that you are concerned with?

1 solution

Something like below could work using ScreenCapture which you could get it from the following link
Screen Capture

and you use it as below

C#
ScreenCapture sc = new ScreenCapture();

Image img = sc.CaptureScreen();

this.imageDisplay.Image = img;

sc.CaptureWindowToFile(this.Handle,@"C:\tmp\pic.gif",ImageFormat.Gif);


i hope this helps
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900