WPF截屏

前言

如果电脑有多屏这里只截取主屏。

C#截屏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void ScreenShot(string savePath)
{
using (Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(0, 0, 0, 0, bmp.Size);
bmp.Save(savePath, ImageFormat.Jpeg);

//MemoryStream data = new MemoryStream();
//bmp.Save(data, ImageFormat.Png);
}
}
}

调用系统DLL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace SchoolClient.Utils
{
public class ZScreenCapture
{
/// <summary>
/// Creates an Image object containing a screen shot of the entire desktop
/// </summary>
/// <returns>
/// </returns>
public static Image CaptureScreen()
{
return CaptureWindow(User32.GetDesktopWindow());
}

public static void CaptureScreenSave(string savePath)
{
using (Image img = CaptureWindow(User32.GetDesktopWindow()))
{
img.Save(savePath, ImageFormat.Jpeg);
}
}

/// <summary>
/// Creates an Image object containing a screen shot of a specific window
/// </summary>
/// <param name="handle">
/// The handle to the window. (In windows forms, this is obtained by the Handle property)
/// </param>
/// <returns>
/// </returns>
private static Image CaptureWindow(IntPtr handle)
{
// get te hDC of the target window
IntPtr hdcSrc = User32.GetWindowDC(handle);
// get the size
User32.RECT windowRect = new User32.RECT();
User32.GetWindowRect(handle, ref windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
// create a device context we can copy to
IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
// create a bitmap we can copy it to, using GetDeviceCaps to get the width/height
IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
// select the bitmap object
IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);
// bitblt over
GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, GDI32.SRCCOPY | GDI32.CAPTUREBLT);
// restore selection
GDI32.SelectObject(hdcDest, hOld);
// clean up
GDI32.DeleteDC(hdcDest);
User32.ReleaseDC(handle, hdcSrc);
// get a .NET image object for it
Image img = Image.FromHbitmap(hBitmap);
// free up the Bitmap object
GDI32.DeleteObject(hBitmap);
return img;
}

/// <summary>
/// Helper class containing Gdi32 API functions
/// </summary>
private class GDI32
{
public const int CAPTUREBLT = 1073741824;
public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter

[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest,
int nWidth, int nHeight, IntPtr hObjectSource,
int nXSrc, int nYSrc, int dwRop);

[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth,
int nHeight);

[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);

[DllImport("gdi32.dll")]
public static extern bool DeleteDC(IntPtr hDC);

[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
}

/// <summary>
/// Helper class containing User32 API functions
/// </summary>
private class User32
{
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}

[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();

[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);

[DllImport("user32.dll")]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);

[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
}
}
}

调用C++DLL

https://www.psvmc.cn/article/2021-07-08-image-cpp.html

调用三方程序

注意

这种方式截屏会导致鼠标光标现在旋转的动画,如果反复调用体验不好,我这里已更换为C#调用C++进行截屏的方式了。

使用nircmd.exe截屏

官网:http://www.nirsoft.net/utils/nircmd.html

链接:https://pan.baidu.com/s/1AyGNHN5XM5v08gjGx3y6Dw
提取码:sytu

1
nircmd.exe savescreenshot "d:\temp.png"

这种方法其实各种语言都可以使用。

首先在项目下放入下载的exe路径:Tools/nircmd.exe

项目右键=>属性=>生成事件=>生成前事件命令行 添加如下

1
xcopy /Y /i /e $(ProjectDir)\Tools $(TargetDir)\Tools

目的是为了打包运行时能够找到 nircmd.exe

工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace SchoolClient.Utils
{
internal class ZScreenUtil2
{
public static bool CaptureScreenSave(string filePath)
{
int lastindex = filePath.LastIndexOf(Path.DirectorySeparatorChar);
if (lastindex < filePath.Length)
{
string fileFolder = filePath.Substring(0, lastindex);
string filename = filePath.Substring(lastindex + 1);
string tempFilePath = fileFolder + Path.DirectorySeparatorChar + "_temp_" + filename;

string basePath = AppDomain.CurrentDomain.BaseDirectory;
string toolsPath = System.IO.Path.Combine(basePath, "Tools");

Process mps = new Process();
ProcessStartInfo mpsi = new ProcessStartInfo("nircmd.exe", "savescreenshot \"" + tempFilePath+"\"" )
{
WorkingDirectory = toolsPath,
UseShellExecute = true,
RedirectStandardInput = false,
RedirectStandardOutput = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
};
mps.StartInfo = mpsi;
mps.Start();
mps.WaitForExit();
mps.Close();

bool result = GetPicThumbnail(tempFilePath, filePath, 1920, 1080, 80, true);
return result;
}
else
{
return false;
}
}

/// 无损压缩图片
/// <param name="sFile">原图片</param>
/// <param name="dFile">压缩后保存位置</param>
/// <param name="dWidth"></param>
/// <param name="dHeight">高度</param>
/// <param name="ratio">压缩质量(数字越小压缩率越高) 1-100</param>
/// <returns></returns>
public static bool GetPicThumbnail(string sFile, string dFile, int dWidth, int dHeight, int ratio, bool deleteSFile)
{
System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
ImageFormat tFormat = iSource.RawFormat;

//按比例缩放
Size tem_size = new Size(iSource.Width, iSource.Height);
int sW;
int sH;
if (tem_size.Width > dHeight || tem_size.Width > dWidth)
{
if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
{
sW = dWidth;
sH = (dWidth * tem_size.Height) / tem_size.Width;
}
else
{
sH = dHeight;
sW = (tem_size.Width * dHeight) / tem_size.Height;
}
}
else
{
sW = tem_size.Width;
sH = tem_size.Height;
}

Bitmap ob = new Bitmap(dWidth, dHeight);
Graphics g = Graphics.FromImage(ob);

g.Clear(Color.WhiteSmoke);
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;

g.DrawImage(
iSource,
new Rectangle((dWidth - sW) / 2,(dHeight - sH) / 2, sW, sH),
0,
0,
iSource.Width,
iSource.Height,
GraphicsUnit.Pixel
);

g.Dispose();
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = ratio;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
try
{
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
if (jpegICIinfo != null)
{
ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
}
else
{
ob.Save(dFile, tFormat);
}
return true;
}
catch
{
return false;
}
finally
{
iSource.Dispose();
ob.Dispose();

if (deleteSFile)
{
FileInfo di = new FileInfo(sFile);
if (di.Exists)
{
try
{
di.Delete();
}
catch (Exception)
{
}
}
}
}
}
}
}

注意在压缩图片前一定要调用

1
2
mps.WaitForExit();
mps.Close();

这样才会在生成图片后进行压缩。