C#控制台程序截图无法捕获全屏,如何获取1980×1080完整截图?
解决1980×1080完整屏幕截图问题
你的代码无法捕获完整屏幕,核心原因是系统高DPI缩放导致Screen.PrimaryScreen.Bounds返回逻辑分辨率而非物理分辨率。当系统开启125%/150%等缩放比例时,逻辑尺寸会小于真实的1980×1080物理分辨率,从而造成截图不完整。
以下是两种可靠的解决方案:
方案一:代码层面启用高DPI感知并获取物理分辨率
直接通过API设置程序的DPI感知能力,再获取屏幕真实物理尺寸:
using Emgu.CV; using Emgu.CV.CvEnum; using Emgu.CV.Structure; using System; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; namespace ScreenCaptureExample { class Program { [DllImport("user32.dll")] private static extern bool SetProcessDpiAwarenessContext(int dpiFlag); private const int DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = 3; [DllImport("gdi32.dll")] private static extern int GetDeviceCaps(IntPtr hdc, int nIndex); private const int HORZRES = 8; // 水平物理像素数 private const int VERTRES = 10; // 垂直物理像素数 static void Main(string[] args) { // 启用高DPI感知,让程序识别真实物理分辨率 SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); Bitmap screenshot = CaptureScreen(); screenshot.Save("D:\\ThisScreenshot.png"); screenshot.Dispose(); Console.WriteLine($"Screenshot has been created."); } static Bitmap CaptureScreen() { using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { IntPtr hdc = g.GetHdc(); // 获取屏幕真实物理分辨率 int screenWidth = GetDeviceCaps(hdc, HORZRES); int screenHeight = GetDeviceCaps(hdc, VERTRES); g.ReleaseHdc(hdc); Bitmap screenshot = new Bitmap(screenWidth, screenHeight); using (Graphics gfx = Graphics.FromImage(screenshot)) { // 从屏幕左上角(0,0)复制完整物理尺寸区域 gfx.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight)); } return screenshot; } } } }
方案二:通过应用程序清单启用高DPI感知
如果不想修改代码,可以添加应用程序清单文件,让系统自动识别程序的高DPI需求:
- 在项目中添加
app.manifest文件 - 找到
<application>节点,替换为以下内容:
<application xmlns="urn:schemas-microsoft-com:asm.v3"> <windowsSettings> <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware> <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness> </windowsSettings> </application>
之后原代码的Screen.PrimaryScreen.Bounds就能正确返回1980×1080的物理分辨率。
内容的提问来源于stack exchange,提问作者Stasich
相关产品推荐
相关产品推荐

