我在截取窗口屏幕截图时遇到问题。
这是我正在使用的代码:
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);
}
}
}
这是结果:
正如你所看到的,图像是空的,我希望得到这样的图像:
我 100% 确定窗口句柄不是问题,因为 GetWindowRect 工作正常
最佳答案
代码中有一个很容易被忽视的小错误。
gfxScreenshot.CopyFromScreen(window.Left,
window.Top, // window.Top instead of window.Right
0,
0,
size,
CopyPixelOperation.SourceCopy);
这里应该使用window.Top
,而不是window.Right
。第二个参数是区域的 Y 坐标。
关于c# - 如何从窗口获取屏幕截图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60131929/