用c#进行截屏时,由于用户可能在显示设置内调整缩放比例,比如“更改文本、应用等项目的大小”到150%。这时,用传统的代码抓屏时就会出现显示区域不全的问题。
原因在于当前显示器的“屏幕分辨率当前物理大小”和屏幕显示大小不一致,对应的获取方法分别如下:
/// <summary>
/// 获取真实设置的桌面分辨率大小
/// </summary>
public static Size DESKTOP
{
get
{
IntPtr hdc = GetDC(IntPtr.Zero);
Size size = new Size();
size.Height = GetDeviceCaps(hdc, 117);
size.Width = GetDeviceCaps(hdc, 118);
ReleaseDC(IntPtr.Zero, hdc);
return size;
}
}
#region Win32 API
[DllImport("user32.dll")]
static extern IntPtr GetDC(IntPtr ptr);
[DllImport("gdi32.dll")]
static extern int GetDeviceCaps(
IntPtr hdc, // handle to DC
int nIndex // index of capability
);
#endregion
//获取屏幕显示大小
Rectangle tScreenRect = Screen.PrimaryScreen.Bounds;
当两者不相同时,需要先按照物理尺寸截屏,然后进行缩放到显示尺寸,代码如下:
/// <summary>
/// 抓屏
/// </summary>
/// <returns></returns>
private Bitmap GetScreenImage()
{
//获取屏幕显示大小
Rectangle viewRect = Screen.PrimaryScreen.Bounds;
Size phisicalRect = DESKTOP;
Bitmap tSrcBmp = new Bitmap(phisicalRect.Width, phisicalRect.Height); // 用于屏幕原始图片保存
Graphics gp = Graphics.FromImage(tSrcBmp);
gp.CopyFromScreen(0, 0, 0, 0, phisicalRect);
if (viewRect.Size != phisicalRect)
{
//当两者不相同时进行缩放
Bitmap tSrcBmp2 = new Bitmap(viewRect.Width, viewRect.Height);
Graphics gp2 = Graphics.FromImage(tSrcBmp2);
gp2.DrawImage(tSrcBmp, new Rectangle(0, 0, viewRect.Width, viewRect.Height), 0, 0, phisicalRect.Width, phisicalRect.Height, GraphicsUnit.Pixel);
return tSrcBmp2 as Bitmap;
}
else {
return tSrcBmp;
}
}