C#轻松获取屏幕尺寸全攻略 从基础代码到多显示器兼容性解决实际开发中的屏幕适配问题

引言:屏幕尺寸获取在现代应用开发中的重要性
在当今多设备、多显示器的计算环境中,正确获取屏幕尺寸和显示器信息对于开发高质量的桌面应用程序至关重要。无论是创建响应式UI、实现窗口管理功能,还是开发屏幕录制、游戏引擎等专业应用,准确的屏幕信息都是基础需求。
C#作为.NET平台的主要语言,提供了多种API来获取屏幕信息,从简单的
Screen
类到复杂的多显示器支持,再到高DPI环境下的精确计算。本文将全面介绍C#中获取屏幕尺寸的各种方法,并重点解决多显示器环境下的兼容性问题。
1. 基础屏幕信息获取:Screen类详解
1.1 Screen类的基本使用
C#中最基础的屏幕信息获取方式是通过
System.Windows.Forms.Screen
类。这个类提供了访问主显示器和所有显示器信息的简单方法。
using System;
using System.Windows.Forms;

public class ScreenInfoDemo
{
public static void GetBasicScreenInfo()
{
// 获取主显示器
Screen primaryScreen = Screen.PrimaryScreen;

Console.WriteLine(“=== 主显示器信息 ===”);
Console.WriteLine($”设备名称: {primaryScreen.DeviceName}”);
Console.WriteLine($”工作区域: {primaryScreen.WorkingArea}”);
Console.WriteLine($”屏幕边界: {primaryScreen.Bounds}”);
Console.WriteLine($”是否为主显示器: {primaryScreen.Primary}”);

// 获取所有显示器
Screen[] allScreens = Screen.AllScreens;
Console.WriteLine($”\n系统共有 {allScreens.Length} 个显示器”);

foreach (Screen screen in allScreens)
{
Console.WriteLine($”显示器: {screen.DeviceName}, 主显示器: {screen.Primary}”);
Console.WriteLine($” 分辨率: {screen.Bounds.Width}x{screen.Bounds.Height}”);
Console.WriteLine($” 工作区域: {screen.WorkingArea.Width}x{screen.WorkingArea.Height}”);
}
}
}
1.2 理解Bounds和WorkingArea的区别
Bounds
和
WorkingArea
是Screen类中两个关键属性,理解它们的区别对于正确处理窗口位置至关重要。
public class ScreenAreaDemo
{
public static void DemonstrateBoundsVsWorkingArea()
{
Screen screen = Screen.PrimaryScreen;

// Bounds: 整个屏幕的像素区域,包括任务栏等系统区域
Console.WriteLine($”Bounds (完整屏幕): {screen.Bounds}”);

// WorkingArea: 屏幕的工作区域,不包括任务栏等停靠的系统区域
Console.WriteLine($”WorkingArea (可用区域): {screen.WorkingArea}”);

// 计算任务栏占用的空间
int taskbarHeight = screen.Bounds.Height – screen.WorkingArea.Height;
int taskbarWidth = screen.Bounds.Width – screen.WorkingArea.Width;

Console.WriteLine($”任务栏高度: {taskbarHeight}px”);
Console.WriteLine($”任务栏宽度: {taskbarWidth}px”);

// 实际应用:将窗口放置在工作区域的中心
int windowWidth = 800;
int windowHeight = 600;

int x = screen.WorkingArea.X + (screen.WorkingArea.Width – windowWidth) / 2;
int y = screen.WorkingArea.Y + (screen.WorkingArea.Height – windowHeight) / 2;

Console.WriteLine($”窗口应放置在: ({x}, {y})”);
}
}
1.3 获取屏幕DPI和缩放比例
现代显示器通常具有不同的DPI(每英寸点数)设置,正确处理DPI对于确保UI正确缩放至关重要。
using System.Drawing;
using System.Windows.Forms;

public class DpiDemo
{
public static void GetScreenDpi()
{
// 获取Graphics对象用于DPI计算
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
{
float dpiX = g.DpiX;
float dpiY = g.DpiY;

Console.WriteLine($”DPI X: {dpiX}”);
Console.WriteLine($”DPI Y: {dpiY}”);

// 计算缩放比例(标准DPI为96)
float scaleX = dpiX / 96.0f;
float scaleY = dpiY / 96.0f;

Console.WriteLine($”缩放比例: {scaleX * 100}%”);
}

// 在.NET Framework 4.7+中,可以使用SystemInformation获取更准确的DPI
if (Environment.Version.Major >= 4 && Environment.Version.Minor >= 7)
{
// 注意:这需要在.NET Framework 4.7+或.NET Core 3.0+
// 实际使用时需要添加对System.Windows.Forms的引用
// 并在项目文件中设置true
}
}
}
2. 多显示器环境下的屏幕管理
2.1 多显示器配置识别
在多显示器环境中,识别每个显示器的相对位置和配置是解决屏幕适配问题的关键。
public class MultiMonitorDemo
{
public static void AnalyzeMultiMonitorSetup()
{
Screen[] screens = Screen.AllScreens;

Console.WriteLine(“=== 多显示器配置分析 ===”);

// 按X坐标排序显示器(从左到右)
var sortedScreens = screens.OrderBy(s => s.Bounds.X).ToArray();

for (int i = 0; i < sortedScreens.Length; i++) { Screen screen = sortedScreens[i]; Console.WriteLine($"\n显示器 {i + 1}:"); Console.WriteLine($" 设备名称: {screen.DeviceName}"); Console.WriteLine($" 位置: ({screen.Bounds.X}, {screen.Bounds.Y})"); Console.WriteLine($" 分辨率: {screen.Bounds.Width}x{screen.Bounds.Height}"); Console.WriteLine($" 工作区域: {screen.WorkingArea}"); // 判断显示器排列方式 if (i > 0)
{
Screen prevScreen = sortedScreens[i – 1];
if (screen.Bounds.X > prevScreen.Bounds.X + prevScreen.Bounds.Width)
{
Console.WriteLine($” 排列: 位于显示器 {i} 的右侧”);
}
else if (screen.Bounds.Y > prevScreen.Bounds.Y + prevScreen.Bounds.Height)
{
Console.WriteLine($” 排列: 位于显示器 {i} 的下方”);
}
else
{
Console.WriteLine($” 排列: 与显示器 {i} 重叠”);
}
}
}
}
}
2.2 跨显示器窗口管理
在多显示器环境中,需要考虑窗口在不同显示器间的移动和定位。
public class CrossMonitorWindowDemo
{
public static void MoveWindowAcrossMonitors()
{
// 示例:将窗口移动到特定显示器的工作区域
// 注意:实际移动窗口需要使用Win32 API或设置Form.Location

Screen targetScreen = GetScreenByName(“\\\\.\\DISPLAY2″);

if (targetScreen != null)
{
// 计算在目标显示器中心的窗口位置
int windowWidth = 800;
int windowHeight = 600;

int x = targetScreen.WorkingArea.X + (targetScreen.WorkingArea.Width – windowWidth) / 2;
int y = targetScreen.WorkingArea.Y + (targetScreen.WorkingArea.Height – windowHeight) / 2;

Console.WriteLine($”窗口应移动到显示器 {targetScreen.DeviceName} 的位置: ({x}, {y})”);

// 在实际WinForms应用中,可以这样设置:
// this.Location = new Point(x, y);
// this.Size = new Size(windowWidth, windowHeight);
}
}

private static Screen GetScreenByName(string deviceName)
{
return Screen.AllScreens.FirstOrDefault(s => s.DeviceName == deviceName);
}

public static void GetScreenFromPoint(Point point)
{
// 根据坐标点获取所在的显示器
Screen screen = Screen.FromPoint(point);
Console.WriteLine($”点 ({point.X}, {point.Y}) 所在的显示器: {screen.DeviceName}”);
}
}
3. 高DPI和缩放比例处理
3.1 高DPI感知设置
在.NET Framework 4.7+和.NET Core 3.0+中,需要正确设置DPI感知模式。
// 在.NET Core 3.0+中,需要在Program.cs中设置
public static class Program
{
[STAThread]
static void Main()
{
// 设置DPI感知模式为PerMonitorV2(需要Windows 10 1703+)
// 这必须在任何UI组件创建之前调用
if (Environment.OSVersion.Version.Major >= 10)
{
// 在.NET Core 3.0+中,可以使用:
// Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
}

// 对于.NET Framework,需要在app.manifest中设置
// 或者使用Win32 API SetProcessDpiAwarenessContext
}
}
3.2 手动计算高DPI下的屏幕尺寸
当需要精确计算高DPI环境下的屏幕尺寸时,需要考虑缩放比例。
public class HighDpiScreenDemo
{
public static void GetScaledScreenInfo()
{
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
{
float dpiX = g.DpiX;
float dpiY = g.DpiY;
float scale = dpiX / 96.0f; // 96是标准DPI

Screen screen = Screen.PrimaryScreen;

// 物理像素
int physicalWidth = screen.Bounds.Width;
int physicalHeight = screen.Bounds.Height;

// 设备无关像素(考虑DPI缩放)
int deviceIndependentWidth = (int)(physicalWidth / scale);
int deviceIndependentHeight = (int)(physicalHeight / scale);

Console.WriteLine($”物理分辨率: {physicalWidth}x{physicalHeight}”);
Console.WriteLine($”设备无关分辨率: {deviceIndependentWidth}x{deviceIndependentHeight}”);
Console.WriteLine($”DPI缩放: {scale * 100}%”);

// 在高DPI下创建控件时,需要考虑缩放
// 例如,创建一个400×300的窗口,在150%缩放下:
int scaledWidth = (int)(400 * scale);
int scaledHeight = (int)(300 * scale);

Console.WriteLine($”400×300窗口在{scale * 100}%缩放下实际大小: {scaledWidth}x{scaledHeight}”);
}
}
}
4. Win32 API高级应用
4.1 使用Win32 API获取更详细的显示器信息
当标准API无法满足需求时,可以使用Win32 API获取更详细的显示器信息。
using System;
using System.Runtime.InteropServices;
using System.Drawing;

public class Win32ScreenApi
{
// 定义Win32常量
public const int ENUM_CURRENT_SETTINGS = -1;
public const int CDS_UPDATEREGISTRY = 0x01;
public const int CDS_TEST = 0x02;
public const int CDS_SET_PRIMARY = 0x10;
public const int CDS_NORESET = 0x10000000;
public const int CDS_FORCE = 0x80000000;

public const int DISP_CHANGE_SUCCESSFUL = 0;
public const int DISP_CHANGE_RESTART = 1;
public const int DISP_CHANGE_FAILED = -1;

// DEVMODE结构体
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct DEVMODE
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmDeviceName;

public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public int dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmFormName;

public short dmLogPixels;
public int dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
}

// Win32函数声明
[DllImport(“user32.dll”)]
public static extern bool EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE devMode);

[DllImport(“user32.dll”)]
public static extern bool EnumDisplayDevices(string deviceName, int devNum, ref DISPLAY_DEVICE displayDevice, int flags);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct DISPLAY_DEVICE
{
public int cb;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string DeviceName;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string DeviceString;

public int StateFlags;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string DeviceID;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string DeviceKey;
}

// 获取显示器详细信息
public static void GetDetailedDisplayInfo()
{
DISPLAY_DEVICE device = new DISPLAY_DEVICE();
device.cb = Marshal.SizeOf(device);

int deviceIndex = 0;

Console.WriteLine(“=== Win32 API 显示器详细信息 ===”);

while (EnumDisplayDevices(null, deviceIndex, ref device, 1))
{
Console.WriteLine($”\n设备 {deviceIndex}:”);
Console.WriteLine($” 名称: {device.DeviceName}”);
Console.WriteLine($” 描述: {device.DeviceString}”);
Console.WriteLine($” 状态: {device.StateFlags}”);
Console.WriteLine($” ID: {device.DeviceID}”);

// 获取当前显示设置
DEVMODE devMode = new DEVMODE();
devMode.dmSize = (short)Marshal.SizeOf(devMode);

if (EnumDisplaySettings(device.DeviceName, ENUM_CURRENT_SETTINGS, ref devMode))
{
Console.WriteLine($” 分辨率: {devMode.dmPelsWidth}x{devMode.dmPelsHeight}”);
Console.WriteLine($” 位深度: {devMode.dmBitsPerPel}”);
Console.WriteLine($” 刷新率: {devMode.dmDisplayFrequency}Hz”);
Console.WriteLine($” 位置: ({devMode.dmPositionX}, {devMode.dmPositionY})”);
}

deviceIndex++;
device = new DISPLAY_DEVICE();
device.cb = Marshal.SizeOf(device);
}
}
}
5. 实际开发中的屏幕适配解决方案
5.1 创建屏幕管理器类
将所有屏幕相关功能封装到一个管理器类中,便于在项目中复用。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

public class ScreenManager
{
private static ScreenManager _instance;
public static ScreenManager Instance => _instance ?? (_instance = new ScreenManager());

public List Screens { get; private set; }
public ScreenInfo PrimaryScreen { get; private set; }

private ScreenManager()
{
RefreshScreens();
}

public void RefreshScreens()
{
Screens = Screen.AllScreens.Select(s => new ScreenInfo(s)).ToList();
PrimaryScreen = Screens.FirstOrDefault(s => s.IsPrimary);
}

// 根据名称获取屏幕
public ScreenInfo GetScreenByName(string deviceName)
{
return Screens.FirstOrDefault(s => s.DeviceName == deviceName);
}

// 根据坐标点获取屏幕
public ScreenInfo GetScreenFromPoint(Point point)
{
var screen = Screen.FromPoint(point);
return Screens.FirstOrDefault(s => s.DeviceName == screen.DeviceName);
}

// 获取最佳屏幕用于显示窗口
public ScreenInfo GetBestScreenForWindow(Rectangle windowBounds)
{
// 优先选择主显示器
if (PrimaryScreen != null && PrimaryScreen.WorkingArea.Contains(windowBounds))
{
return PrimaryScreen;
}

// 否则选择包含窗口最多的屏幕
return Screens.OrderByDescending(s =>
Rectangle.Intersect(s.WorkingArea, windowBounds).Area)
.FirstOrDefault();
}

// 计算窗口在指定屏幕的中心位置
public Point GetCenterPosition(ScreenInfo screen, Size windowSize)
{
return new Point(
screen.WorkingArea.X + (screen.WorkingArea.Width – windowSize.Width) / 2,
screen.WorkingArea.Y + (screen.WorkingArea.Height – windowSize.Height) / 2
);
}

// 检查窗口是否完全在某个屏幕内
public bool IsWindowFullyOnScreen(Rectangle windowBounds, ScreenInfo screen)
{
return screen.WorkingArea.Contains(windowBounds);
}

// 获取窗口应该移动到的屏幕(当窗口部分在屏幕外时)
public ScreenInfo GetScreenToMoveWindow(Rectangle windowBounds)
{
// 找到包含窗口中心点最多的屏幕
Point center = new Point(
windowBounds.X + windowBounds.Width / 2,
windowBounds.Y + windowBounds.Height / 2
);

return GetScreenFromPoint(center);
}
}

// 屏幕信息包装类
public class ScreenInfo
{
public string DeviceName { get; }
public Rectangle Bounds { get; }
public Rectangle WorkingArea { get; }
public bool IsPrimary { get; }
public float DpiX { get; }
public float DpiY { get; }
public float ScaleFactor { get; }

public ScreenInfo(Screen screen)
{
DeviceName = screen.DeviceName;
Bounds = screen.Bounds;
WorkingArea = screen.WorkingArea;
IsPrimary = screen.Primary;

// 获取DPI信息
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
{
DpiX = g.DpiX;
DpiY = g.DpiY;
ScaleFactor = DpiX / 96.0f;
}
}

public override string ToString()
{
return $”{DeviceName} ({Bounds.Width}x{Bounds.Height}) – {ScaleFactor * 100}% DPI”;
}
}
5.2 使用ScreenManager的完整示例
public class ScreenManagerUsageDemo
{
public static void DemonstrateScreenManager()
{
var screenManager = ScreenManager.Instance;

Console.WriteLine(“=== ScreenManager 使用示例 ===”);

// 显示所有屏幕信息
foreach (var screen in screenManager.Screens)
{
Console.WriteLine(screen.ToString());
}

// 获取主屏幕
var primary = screenManager.PrimaryScreen;
if (primary != null)
{
Console.WriteLine($”\n主屏幕: {primary}”);

// 计算窗口在主屏幕中心的位置
var centerPos = screenManager.GetCenterPosition(primary, new Size(800, 600));
Console.WriteLine($”800×600窗口在主屏幕中心的位置: {centerPos}”);
}

// 检查窗口位置
var testWindow = new Rectangle(100, 100, 800, 600);
var currentScreen = screenManager.GetScreenFromPoint(testWindow.Location);

if (currentScreen != null)
{
bool isFullyOnScreen = screenManager.IsWindowFullyOnScreen(testWindow, currentScreen);
Console.WriteLine($”\n窗口 {testWindow} 是否完全在屏幕 {currentScreen.DeviceName} 内: {isFullyOnScreen}”);

if (!isFullyOnScreen)
{
var bestScreen = screenManager.GetScreenToMoveWindow(testWindow);
Console.WriteLine($”建议移动到屏幕: {bestScreen.DeviceName}”);
}
}

// 处理多显示器配置变化
// 在实际应用中,可以监听系统设置变化事件
// Microsoft.Win32.SystemEvents.DisplaySettingsChanged += (s, e) => screenManager.RefreshScreens();
}
}
6. 处理显示器配置变化
6.1 监听显示器变化事件
在实际应用中,用户可能会动态连接或断开显示器,需要监听这些变化。
using Microsoft.Win32;

public class DisplayChangeMonitor
{
private ScreenManager _screenManager;

public DisplayChangeMonitor()
{
_screenManager = ScreenManager.Instance;

// 监听显示器配置变化
SystemEvents.DisplaySettingsChanged += OnDisplaySettingsChanged;

// 监听显示器连接/断开(需要Windows Vista+)
SystemEvents.DisplayDevicesChanged += OnDisplayDevicesChanged;
}

private void OnDisplaySettingsChanged(object sender, EventArgs e)
{
Console.WriteLine(“检测到显示器设置变化,刷新屏幕信息…”);
_screenManager.RefreshScreens();

// 在这里可以触发自定义事件,通知应用程序其他部分
OnScreenConfigurationChanged?.Invoke(this, EventArgs.Empty);
}

private void OnDisplayDevicesChanged(object sender, EventArgs e)
{
Console.WriteLine(“检测到显示器设备变化(连接/断开)…”);
_screenManager.RefreshScreens();

OnScreenConfigurationChanged?.Invoke(this, EventArgs.Empty);
}

public event EventHandler OnScreenConfigurationChanged;

// 清理资源
public void Dispose()
{
SystemEvents.DisplaySettingsChanged -= OnDisplaySettingsChanged;
SystemEvents.DisplayDevicesChanged -= OnDisplayDevicesChanged;
}
}
6.2 自动调整窗口位置
当显示器配置变化时,自动调整窗口位置以确保其可见。
public class AutoAdjustWindowDemo
{
public static void AutoAdjustWindowPosition(Form form)
{
var screenManager = ScreenManager.Instance;

// 检查窗口当前是否在任何屏幕内
var currentScreen = screenManager.GetScreenFromPoint(form.Location);

if (currentScreen == null || !screenManager.IsWindowFullyOnScreen(form.Bounds, currentScreen))
{
// 窗口不在任何屏幕内或部分在屏幕外,需要调整
var bestScreen = screenManager.GetScreenToMoveWindow(form.Bounds);

if (bestScreen != null)
{
// 将窗口移动到最佳屏幕的中心
var newPos = screenManager.GetCenterPosition(bestScreen, form.Size);
form.Location = newPos;

Console.WriteLine($”窗口已自动调整到屏幕 {bestScreen.DeviceName} 的中心位置”);
}
else
{
// 没有找到合适的屏幕,移动到主屏幕
var primary = screenManager.PrimaryScreen;
if (primary != null)
{
var newPos = screenManager.GetCenterPosition(primary, form.Size);
form.Location = newPos;
Console.WriteLine($”窗口已移动到主屏幕中心”);
}
}
}
}
}
7. 完整的屏幕适配解决方案
7.1 创建完整的屏幕适配器类
using System;
using System.Drawing;
using System.Windows.Forms;

public class ScreenAdapter
{
private readonly ScreenManager _screenManager;
private readonly DisplayChangeMonitor _displayMonitor;

public ScreenAdapter()
{
_screenManager = ScreenManager.Instance;
_displayMonitor = new DisplayChangeMonitor();
_displayMonitor.OnScreenConfigurationChanged += OnScreenConfigurationChanged;
}

// 确保窗口在可见的屏幕区域内
public bool EnsureWindowVisible(Form form)
{
// 检查窗口是否完全在某个屏幕内
foreach (var screen in _screenManager.Screens)
{
if (screen.WorkingArea.Contains(form.Bounds))
{
return true; // 窗口已经可见
}
}

// 窗口不可见,需要调整
return MoveWindowToVisibleArea(form);
}

// 将窗口移动到可见区域
private bool MoveWindowToVisibleArea(Form form)
{
// 优先尝试移动到主屏幕
if (_screenManager.PrimaryScreen != null)
{
var newPos = _screenManager.GetCenterPosition(_screenManager.PrimaryScreen, form.Size);
form.Location = newPos;
return true;
}

// 如果没有主屏幕,尝试其他屏幕
foreach (var screen in _screenManager.Screens)
{
var newPos = _screenManager.GetCenterPosition(screen, form.Size);
form.Location = newPos;
return true;
}

return false; // 没有找到可用屏幕
}

// 优化窗口位置:确保窗口在合适的屏幕上
public void OptimizeWindowPosition(Form form, WindowOptimizationStrategy strategy)
{
switch (strategy)
{
case WindowOptimizationStrategy.PrimaryScreen:
if (_screenManager.PrimaryScreen != null)
{
var newPos = _screenManager.GetCenterPosition(_screenManager.PrimaryScreen, form.Size);
form.Location = newPos;
}
break;

case WindowOptimizationStrategy.LargestScreen:
var largestScreen = _screenManager.Screens.OrderByDescending(s => s.Bounds.Area).FirstOrDefault();
if (largestScreen != null)
{
var newPos = _screenManager.GetCenterPosition(largestScreen, form.Size);
form.Location = newPos;
}
break;

case WindowOptimizationStrategy.ClosestToCursor:
// 获取当前鼠标位置
Point cursorPos = Cursor.Position;
var closestScreen = _screenManager.GetScreenFromPoint(cursorPos);
if (closestScreen != null)
{
var newPos = _screenManager.GetCenterPosition(closestScreen, form.Size);
form.Location = newPos;
}
break;
}
}

// 处理屏幕配置变化
private void OnScreenConfigurationChanged(object sender, EventArgs e)
{
// 在这里可以触发UI更新或重新布局
Console.WriteLine(“屏幕配置已变化,正在重新评估窗口位置…”);

// 可以在这里添加自定义逻辑,例如:
// – 重新布局所有窗口
// – 更新UI元素大小
// – 重新计算布局坐标
}

// 获取多显示器工作区域
public Rectangle GetTotalWorkingArea()
{
if (_screenManager.Screens.Count == 0)
return Rectangle.Empty;

// 计算所有屏幕工作区域的并集
int minX = _screenManager.Screens.Min(s => s.WorkingArea.X);
int minY = _screenManager.Screens.Min(s => s.WorkingArea.Y);
int maxX = _screenManager.Screens.Max(s => s.WorkingArea.X + s.WorkingArea.Width);
int maxY = _screenManager.Screens.Max(s => s.WorkingArea.Y + s.WorkingArea.Height);

return new Rectangle(minX, minY, maxX – minX, maxY – minY);
}

// 检查窗口是否在多显示器配置下有效
public bool IsWindowPositionValid(Rectangle windowBounds)
{
// 检查窗口是否至少部分在某个屏幕内
return _screenManager.Screens.Any(s => s.Bounds.IntersectsWith(windowBounds));
}

public void Dispose()
{
_displayMonitor?.Dispose();
}
}

public enum WindowOptimizationStrategy
{
PrimaryScreen,
LargestScreen,
ClosestToCursor
}
7.2 在WinForms应用中使用ScreenAdapter
public partial class MainForm : Form
{
private ScreenAdapter _screenAdapter;

public MainForm()
{
InitializeComponent();
_screenAdapter = new ScreenAdapter();

// 确保窗口在可见区域
this.Load += (s, e) => _screenAdapter.EnsureWindowVisible(this);

// 监听屏幕变化
Microsoft.Win32.SystemEvents.DisplaySettingsChanged += (s, e) =>
{
// 延迟执行,确保系统完成配置
this.BeginInvoke(new Action(() =>
{
_screenAdapter.EnsureWindowVisible(this);
}));
};
}

protected override void OnFormClosing(FormClosingEventArgs e)
{
_screenAdapter?.Dispose();
base.OnFormClosing(e);
}
}
8. 总结与最佳实践
8.1 关键要点总结
基础API使用
:
Screen.PrimaryScreen
和
Screen.AllScreens
是获取屏幕信息的基础
Bounds vs WorkingArea
:理解这两个属性的区别对于正确处理窗口位置至关重要
多显示器支持
:需要考虑显示器的相对位置和配置
高DPI处理
:现代应用必须正确处理DPI缩放
动态配置变化
:应用程序应该能够响应显示器连接/断开事件
8.2 性能优化建议
缓存屏幕信息
:避免频繁调用Screen.AllScreens,使用缓存
延迟处理
:处理屏幕变化事件时,使用延迟确保系统稳定
异步更新
:在UI线程外处理复杂的屏幕计算
8.3 兼容性考虑
.NET Framework vs .NET Core
:注意API差异
Windows版本兼容性
:某些功能需要Windows 10+或Windows 8+
32位 vs 64位
:Win32 API调用需要注意平台兼容性
通过本文介绍的方法和示例代码,开发者可以构建健壮的屏幕适配解决方案,确保应用程序在各种显示器配置下都能正常工作。无论是简单的窗口定位,还是复杂的多显示器应用,这些技术都能提供可靠的屏幕信息获取和处理能力。