c# - 如何捕获屏幕的一部分

标签 c# winapi screen-scraping screen-capture

我正在使用 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;
}

请注意,我是从 this blog 中拉下来的

关于c# - 如何捕获屏幕的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3241220/

相关文章:

c# - 将所有传出网络流量设置为通过某个代理

c# - 使用代码调用任务进行单元测试同步方法

c# - XNA GameTime Windows 手机

c# - WebRequest - .timeout 问题

python - 如果 [string] 中的 [string] 不适用于请求的网页文本

c# - 如何像 Windows 应用程序中的人一样以编程方式在网页上冲浪?

c++ - 无法使用 LoadIcon WINAPI 从资源加载图标

winapi - “some.exe” : 0xC0000005: Access violation executing location 0x00FF1230中0x00FF1230的未处理异常

c++ - 如何在 C++ 中使用 HRESULT 条件检查

java - 使用 JSoup for Java 从网页中提取特定行