如何在 WPF 应用中获取活动屏幕的尺寸?
                           
天天向上
发布: 2024-12-25 00:51:01

原创
62 人浏览过

在 WPF 应用程序中,可以通过 System.Windows.Forms.Screen 类或者 System.Windows.SystemParameters 来获取活动屏幕的尺寸。


方法 1:使用 System.Windows.Forms.Screen

System.Windows.Forms.Screen 类提供了详细的屏幕信息,包括当前活动屏幕的工作区和分辨率。

步骤

  1. 添加对 System.Windows.Forms 的引用。
  2. 使用 Screen.FromHandleScreen.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
发表回复 0

Your email address will not be published. Required fields are marked *