Determine screen size with .NET Core 5?

Viewed 2164

How to determine the screen size with .NET Core? I want to take a screenshot as described in DotNetCore Capture A Screenshot in Windows but they use a fixed 1920*1080 resolution which does not work for my purposes.

Do I have to reference System.Windows.Forms and thereby being nailed down to Windows?

Before switching to .NET Core we used System.Windows.Forms like so:

new Size
{
  Width = Screen.AllScreens.Sum(s => s.Bounds.Width),
  Height = Screen.AllScreens.Max(s => s.Bounds.Height)
}

Which is something we could use again, but we would love something platform-independent of course.

2 Answers

The comments hint that it is not supported yet.

So I show you what we have done to implement it using Windows Forms (took me some time to understand how to reference Windows Forms in a .NET Core library project correctly):

You can add the Windows Forms dependency like so to the csproj file:

<ItemGroup>
  <FrameworkReference Include="Microsoft.WindowsDesktop.App.WindowsForms" />
</ItemGroup>

Then you can use the Screen class again:

new Size
{
  Width = Screen.AllScreens.Sum(s => s.Bounds.Width),
  Height = Screen.AllScreens.Max(s => s.Bounds.Height)
}

IMPORTANT: This works on Windows only, but at least it is .NET Core compatible.

For WPF solution we just used method for maximize window, take values of Width and Height of window, then return window in normal state. Also can be done with dummy second transparent window (use WindowStartupLocation.CenterOwner). Take taskbar in account which is not measured.

Related