如何在 WPF 应用中获取活动屏幕的尺寸?
在 WPF 应用程序中,可以通过
System.Windows.Forms.Screen类或者System.Windows.SystemParameters来获取活动屏幕的尺寸。
方法 1:使用 System.Windows.Forms.Screen 类
System.Windows.Forms.Screen 类提供了详细的屏幕信息,包括当前活动屏幕的工作区和分辨率。
步骤
- 添加对
System.Windows.Forms的引用。 - 使用
Screen.FromHandle或Screen.FromPoint获取特定窗口或点所在的屏幕。
示例代码
using System;
using System.Windows;
using System.Windows.Forms; // 引用此命名空间
using System.Runtime.InteropServices;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// 获取当前窗口句柄
var helper = new System.Windows.Interop.WindowInteropHelper(this);
IntPtr hwnd = helper.Handle;
// 获取窗口所在的屏幕
Screen currentScreen = Screen.FromHandle(hwnd);
// 屏幕分辨率
int screenWidth = currentScreen.Bounds.Width;
int screenHeight = currentScreen.Bounds.Height;
// 工作区尺寸(排除任务栏等)
int workAreaWidth = currentScreen.WorkingArea.Width;
int workAreaHeight = currentScreen.WorkingArea.Height;
// 显示结果
MessageBox.Show($"屏幕分辨率: {screenWidth}x{screenHeight}\n工作区尺寸: {workAreaWidth}x{workAreaHeight}");
}
}
方法 2:使用 System.Windows.SystemParameters
如果只需要获取主屏幕的尺寸,可以使用 WPF 的内置 SystemParameters。
示例代码
using System.Windows;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// 主屏幕的全屏分辨率
double screenWidth = SystemParameters.PrimaryScreenWidth;
double screenHeight = SystemParameters.PrimaryScreenHeight;
// 主屏幕的工作区尺寸(排除任务栏等)
double workAreaWidth = SystemParameters.WorkArea.Width;
double workAreaHeight = SystemParameters.WorkArea.Height;
// 显示结果
MessageBox.Show($"屏幕分辨率: {screenWidth}x{screenHeight}\n工作区尺寸: {workAreaWidth}x{workAreaHeight}");
}
}
方法对比
| 方法 | 使用场景 | 优点 | 缺点 |
|---|---|---|---|
System.Windows.Forms.Screen | 获取多屏幕或活动屏幕的尺寸 | 支持多屏幕,功能强大 | 需要添加额外引用 |
System.Windows.SystemParameters | 获取主屏幕尺寸 | 简单易用,无需外部引用 | 只支持主屏幕,不支持多屏幕 |
总结
- 如果应用程序需要支持多屏幕场景,建议使用
System.Windows.Forms.Screen。 - 如果只需要主屏幕的信息且不想添加额外引用,可以使用
System.Windows.SystemParameters。