[英]How to get a screenshot from a window?
I'm having trouble by taking a screenshot of a window.我在截取窗口的屏幕截图时遇到了问题。
This is the code I'm using:这是我正在使用的代码:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace Alerts
{
class ImgSearch
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow(string strClassName, string strWindowName);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle);
public struct Rect
{
public int Left { get; set; }
public int Top { get; set; }
public int Right { get; set; }
public int Bottom { get; set; }
}
public static void ScreenShotWindow(IntPtr whandle)
{
// Get the window rectangle
Rect window = new Rect();
GetWindowRect(whandle, ref window);
// Get window size
int width = window.Right - window.Left;
int height = window.Bottom - window.Top;
Size size = new Size();
size.Width = width;
size.Height = height;
//Create a new bitmap.
var bmpScreenshot = new Bitmap(width,
height,
PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);
// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(window.Left,
window.Right,
0,
0,
size,
CopyPixelOperation.SourceCopy);
// Save the screenshot to the specified path that the user has chosen.
bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);
}
}
}
This is the result:这是结果:
So as you can see the image is empty, and I expected to get an image like this:所以你可以看到图像是空的,我希望得到这样的图像:
I'm 100% sure the window handle is not the problem because GetWindowRect is working perfectly我 100% 确定窗口句柄不是问题,因为 GetWindowRect 工作正常
There is a small mistake in the code that can be easily overlooked.代码中有一个很容易被忽略的小错误。
gfxScreenshot.CopyFromScreen(window.Left,
window.Top, // window.Top instead of window.Right
0,
0,
size,
CopyPixelOperation.SourceCopy);
Instead of window.Right
you should use window.Top
here.取而代之的window.Right
你应该使用window.Top
这里。 The second parameter is the Y coordinate of the area.第二个参数是区域的 Y 坐标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.