C# 自动自定义截图的内容
C# 自动自定义截图的内容
using System;
using System.Drawing;
using System.Runtime.InteropServices;
class Program
{[DllImport("user32.dll")]public static extern IntPtr GetDesktopWindow();[DllImport("user32.dll")]public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rectangle rect);[DllImport("user32.dll")]public static extern IntPtr GetForegroundWindow();[DllImport("user32.dll")]public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);[DllImport("gdi32.dll")]public static extern bool DeleteObject(IntPtr hObject);[DllImport("gdi32.dll")]public static extern IntPtr CreateDC(string lpszDriver, string lpszDevice, string lpszOutput, IntPtr lpInitData);[DllImport("user32.dll")]public static extern IntPtr GetDC(IntPtr hWnd);const uint PW_CLIENTONLY = 0x00000001;public static Bitmap CaptureActiveWindow(){IntPtr hwnd = GetForegroundWindow(); // 获取当前活动窗口句柄Rectangle rect = new Rectangle();GetWindowRect(hwnd, ref rect); // 获取窗口的大小和位置int width = rect.Width - rect.X;int height = rect.Height - rect.Y;IntPtr hdcScreen = GetDC(hwnd); // 获取屏幕设备上下文IntPtr hdcMemory = CreateDC("DISPLAY", null, null, IntPtr.Zero); // 创建内存设备上下文IntPtr hbitmap = IntPtr.Zero;Graphics gCapture = Graphics.FromHdc(hdcMemory); // 从内存设备上下文创建Graphics对象try{hbitmap = PrintWindow(hwnd, hdcMemory, PW_CLIENTONLY); // 捕捉窗口Bitmap bmp = new Bitmap(width, height, gCapture);Graphics g = Graphics.FromImage(bmp);IntPtr hOldBitmap = SelectObject(hdcMemory, hbitmap);g.CopyFromScreen(rect.Left, rect.Top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy);SelectObject(hdcMemory, hOldBitmap);return bmp;}finally{DeleteObject(hbitmap);gCapture.Dispose();ReleaseDC(hwnd, hdcScreen);ReleaseDC(hwnd, hdcMemory);}}[DllImport("gdi32.dll")]public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);[DllImport("user32.dll")]public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
}
使用方法
class Program
{static void Main(string[] args){Bitmap bmp = CaptureActiveWindow();bmp.Save("screenshot.png");}// ... 之前声明的API函数 ...
}