通过手柄捕获窗口的屏幕 [英] Capture screen of Window by handle
本文介绍了通过手柄捕获窗口的屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图仅捕获桌面中的特定窗口,但是却得到了混合图像,窗口的一部分和桌面区域的一部分.
I'm trying to capture only a specific Window in the desktop but I'm getting a mixed image, part of window and part desktop area.
我想念什么?
这是我的代码:
RECT rect = new RECT();
if (!SetForegroundWindow(handle))
throw new Win32Exception(Marshal.GetLastWin32Error());
if (!GetWindowRect(handle, out rect))
throw new Win32Exception(Marshal.GetLastWin32Error());
Thread.Sleep(500);
Rectangle windowSize = rect.ToRectangle();
Bitmap target = new Bitmap(windowSize.Width, windowSize.Height);
using (Graphics g = Graphics.FromImage(target))
{
g.CopyFromScreen(0, 0, 0, 0, new Size(windowSize.Width, windowSize.Height));
}
target.Save("foo.png", System.Drawing.Imaging.ImageFormat.Png);
推荐答案
我认为您的代码中存在以下问题:
I think the problem in your code is this line:
g.CopyFromScreen(0, 0, 0, 0, new Size(windowSize.Width, windowSize.Height));
应该是:
g.CopyFromScreen(windowSize.X, windowSize.Y, 0, 0, new Size(windowSize.Width, windowSize.Height));
这是我个人用来获取特定窗口图像的方法-可能会派上用场:
Here is the method I personally use to get an image of a particular window - it might come in handy:
public Bitmap GetScreenshot()
{
IntPtr hwnd = ihandle;//handle here
RECT rc;
Win32.GetWindowRect(new HandleRef(null, hwnd), out rc);
Bitmap bmp = new Bitmap(rc.Right - rc.Left, rc.Bottom - rc.Top, PixelFormat.Format32bppArgb);
Graphics gfxBmp = Graphics.FromImage(bmp);
IntPtr hdcBitmap;
try
{
hdcBitmap = gfxBmp.GetHdc();
}
catch
{
return null;
}
bool succeeded = Win32.PrintWindow(hwnd, hdcBitmap, 0);
gfxBmp.ReleaseHdc(hdcBitmap);
if (!succeeded)
{
gfxBmp.FillRectangle(new SolidBrush(Color.Gray), new Rectangle(Point.Empty, bmp.Size));
}
IntPtr hRgn = Win32.CreateRectRgn(0, 0, 0, 0);
Win32.GetWindowRgn(hwnd, hRgn);
Region region = Region.FromHrgn(hRgn);//err here once
if (!region.IsEmpty(gfxBmp))
{
gfxBmp.ExcludeClip(region);
gfxBmp.Clear(Color.Transparent);
}
gfxBmp.Dispose();
return bmp;
}
这篇关于通过手柄捕获窗口的屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文