如何使用c#中的代码截取屏幕截图? [英] How to take screenshots using code in c#?

查看:136
本文介绍了如何使用c#中的代码截取屏幕截图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





实际上,我使用的是白色自动化框架,需要截取并比较图像,但我在截屏时遇到问题。同时截取多次相同窗口大小的图像截图。请让我知道任何解决方案,以获取固定大小的活动窗口的屏幕截图。如果多次截取相同窗口的屏幕截图,则不应该有所不同。

我的代码是这样的...

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...

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!

推荐答案

下面的内容可以使用ScreenCapture你可以从以下链接获得它

屏幕截图



你用它如下



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

and you use it as below

ScreenCapture sc = new ScreenCapture();

Image img = sc.CaptureScreen();

this.imageDisplay.Image = img;

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





i希望这有帮助



i hope this helps


这篇关于如何使用c#中的代码截取屏幕截图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆