.NET Core全屏截图,C#全屏截图
.NET Core全屏截图,C#全屏截图
使用框架:
- WPF
- .NET 8
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Runtime.InteropServices;
using System.IO;
namespace WpfAppYolo11_test1.Tool
{
/// <summary>
/// 屏幕全屏截图
/// </summary>
public class ScrentCapter
{
[DllImport("User32.dll", EntryPoint = "GetDC")]
private extern static IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
public static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
const int DESKTOPVERTRES = 117;
const int DESKTOPHORZRES = 118;
/// <summary>
/// 截取电脑全屏图片
/// </summary>
public static string Screenshot()
{
// 获取屏幕的尺寸
IntPtr hdc = GetDC(IntPtr.Zero);
//屏幕宽度
int width = GetDeviceCaps(hdc, DESKTOPHORZRES);
//屏幕高度
int height = GetDeviceCaps(hdc, DESKTOPVERTRES);
System.Drawing.Size size = new System.Drawing.Size()
{
Width = width,
Height = height
};
string filePath = string.Empty;
// 创建一个Bitmap对象,用于存储屏幕截图
using (Bitmap bitmap = new Bitmap(width, height))
{
// 创建一个Graphics对象,用于绘制到Bitmap上
using (Graphics g = Graphics.FromImage(bitmap))
{
// 截取屏幕内容到Graphics对象中
g.CopyFromScreen(0, 0, 0, 0, size);
}
// 保存Bitmap为图片文件
string dir = Path.Combine(AppContext.BaseDirectory, "screen");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
filePath =Path.Combine(dir, $"screen{DateTime.Now.ToString("yyyyMMdd_HHmmssfff")}.png");
bitmap.Save(filePath, ImageFormat.Png);
}
return filePath;
}
}
}