Unity3D调用WINAPI函数对系统窗口截图

引入WINAPI函数

using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Drawing;

  [DllImport("user32.dll")]
  private static extern IntPtr GetDC(IntPtr hwnd);
  [DllImport("user32.dll")]
  private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rectangle rect);
  [DllImport("gdi32.dll")]
  private static extern IntPtr CreateCompatibleDC(IntPtr hdc);
  [DllImport("gdi32.dll")]
  private static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);
  [DllImport("gdi32.dll")]
  private static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
  [DllImport("gdi32.dll")]
  private static extern bool BitBlt(IntPtr hDestDC, int xDest, int yDest, int wDest, int hDest, IntPtr hSrcDC, int xSrc, int ySrc, int rop);
  const int SRCCOPY = 0x00CC0020;
  [DllImport("gdi32.dll")]
  public static extern int GetBitmapBits(IntPtr hbmp, int cbBuffer, byte[] lpvBits);
  [DllImport("gdi32.dll")]
  private static extern int DeleteDC(IntPtr hdc);
  [DllImport("user32.dll")]
  public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
  [DllImport("gdi32.dll")]
  public static extern bool DeleteObject(IntPtr hObject);
  [DllImport("user32.dll")]
  private static extern IntPtr GetDesktopWindow();
  [DllImport("user32.dll")]
  private static extern IntPtr GetActiveWindow();

调用WINAPI函数进行截图

  public static Texture2D CaptureWindow(IntPtr hWnd)
  {
    var hscrdc = GetDC(hWnd);
    var windowRect = new Rectangle();
    GetWindowRect(hWnd, ref windowRect);
    int width = Math.Abs(windowRect.Width - windowRect.X);
    int height = Math.Abs(windowRect.Height - windowRect.Y); 
    
    Texture2D texture = new Texture2D(width, height, TextureFormat.RGBA32, false);

    var hbitmap = CreateCompatibleBitmap(hscrdc, width, height);
    var hmemdc = CreateCompatibleDC(hscrdc);
    SelectObject(hmemdc, hbitmap);
    BitBlt(hmemdc, 0, 0, width, height, hscrdc, 0, 0, SRCCOPY);

    // 创建一个字节数组来存储像素数据
    byte[] pixels = new byte[width * height * 4];

    // 调用 GetBitmapBits 函数,将像素数据存储在字节数组中
    int result = GetBitmapBits(hbitmap, pixels.Length, pixels);

    // 检查结果并处理像素数据
    if (result != 0)
    {
      // 处理像素数据
      texture.LoadRawTextureData(pixels);
      texture.Apply();
    }
    else
    {
      Debug.LogError("Failed to retrieve bitmap bits.");
    }
    DeleteObject(hbitmap);
    ReleaseDC(hWnd, hscrdc);
    DeleteDC(hmemdc);
    return texture;
  }

使用例子

   IntPtr hwnd = GetActiveWindow();
   Texture2D texture = CaptureWindow(hwnd);
   IntPtr hwnd = GetDesktopWindow();
   Texture2D texture = CaptureWindow(hwnd);
09-30 05:02