如何捕获屏幕的一部分

2024-01-06

我正在使用 win32 PrintWindow 函数将屏幕捕获到 BitMap 对象。

如果我只想捕获窗口的一部分区域,如何裁剪内存中的图像?

这是我用来捕获整个窗口的代码:

[System.Runtime.InteropServices.DllImport(strUSER32DLL, CharSet = CharSet.Auto, SetLastError = true)]
public static extern int PrintWindow(IntPtr hWnd, IntPtr hBltDC, uint iFlags);

public enum enPrintWindowFlags : uint
{
    /// <summary>
    /// 
    /// </summary>
    PW_ALL = 0x00000000,
    /// <summary>
    /// Only the client area of the window is copied. By default, the entire window is copied.
    /// </summary>
    PW_CLIENTONLY = 0x00000001
}

public System.Drawing.Bitmap CaptureWindow(IntPtr hWnd, enPrintWindowFlags eFlags)
{
    System.Drawing.Rectangle rctForm = System.Drawing.Rectangle.Empty;

    using(System.Drawing.Graphics grfx = System.Drawing.Graphics.FromHdc(GetWindowDC(hWnd)))
    {
        rctForm = System.Drawing.Rectangle.Round(grfx.VisibleClipBounds);
    }

    System.Drawing.Bitmap pImage = new System.Drawing.Bitmap(rctForm.Width, rctForm.Height);
    System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(pImage);

    IntPtr hDC = graphics.GetHdc();        
    //paint control onto graphics using provided options        
    try 
    {            
        PrintWindow(hWnd, hDC, (uint)eFlags);     
    } 
    finally 
    {            
        graphics.ReleaseHdc(hDC);        
    }    
    return pImage;
}

您可以简单地抓取整个屏幕,然后将图像传递到裁剪函数中,该函数选择整个图像的一个区域。看一下 Bitmap.Clone() 方法。例如

public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
{
Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
return cropped;
}

注意,我把它从这个博客 http://www.nerdydork.com/crop-an-image-bitmap-in-c-or-vbnet.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何捕获屏幕的一部分 的相关文章

随机推荐