Home >Backend Development >C++ >How to Get the Active Screen's Dimensions in WPF?

How to Get the Active Screen's Dimensions in WPF?

Susan Sarandon
Susan SarandonOriginal
2025-01-05 14:49:41749browse

How to Get the Active Screen's Dimensions in WPF?

How to Obtain the Dimensions of the Currently Active Screen in WPF

In the realm of multi-screen setups, it becomes crucial to accurately determine the size of the screen on which an application is displayed. While WPF provides access to the primary screen's dimensions via SystemParameters.PrimaryScreenWidth and SystemParameters.PrimaryScreenHeight, this may not always suffice.

To address this limitation, a custom solution can be implemented using the Screen class from the System.Windows.Forms namespace. This approach offers the ability to retrieve the screen size from XAML or C# code.

The code snippet below encapsulates the functionality in a C# class:

public class WpfScreen
{
    // ... (class definition and methods)
}

Usage:

  • XAML: Accessing the current screen's dimensions from XAML is not directly available through this class.
  • C#: Use the following methods to obtain the screen size:

    • WpfScreen.AllScreens() returns a list of all available screens.
    • WpfScreen.GetScreenFrom(Window) retrieves the screen on which a specified window is displayed.
    • WpfScreen.GetScreenFrom(Point) returns the screen that contains a specific point.
    • WpfScreen.Primary provides access to the primary screen.

Example:

WpfScreen currentScreen = WpfScreen.GetScreenFrom(Window.GetWindow(this));

double screenWidth = currentScreen.DeviceBounds.Width;
double screenHeight = currentScreen.DeviceBounds.Height;

This class provides a convenient way to determine the dimensions of the active screen, enabling accurate application placement and size adjustments in multi-monitor environments.

The above is the detailed content of How to Get the Active Screen's Dimensions in WPF?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn