0

How would I get primary screen size in C# (primarily width) with avalonia (for MS Windows)? Getting screen size through SystemParameters, i.e. System.Windows.SystemParameters.PrimaryScreenWidth, does not work here.

Miljac
  • 2,045
  • 4
  • 19
  • 28
  • Please explain what you mean by "does not work here" - what does `PrimaryScreenWidth` return, exactly? – Dai Jul 12 '23 at 12:38
  • I'm not sure If it's a tied to .net6 or specific to AvaloniaUI, but namespace "System.Windows.SystemParameters" is not available in project. – Miljac Jul 12 '23 at 13:01
  • Maybe Avalonia is using WinForms. You want to use a WPF extension. Does this work? int Width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width; int Height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height; – Marc Wittmann Jul 13 '23 at 12:52
  • Tried it, it doesn't work. But if I understand correctly, Avalonia is built on WPF, although it is not exactly the same – Miljac Jul 13 '23 at 13:06

1 Answers1

0

I checked it works. Unless only for Windows, but based on the question, this is not a problem. https://stackoverflow.com/a/43656496

static class DisplayTools
{
    [DllImport("gdi32.dll")]
    static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

    private enum DeviceCap
    {
        Desktopvertres = 117,
        Desktophorzres = 118
    }

    public static Size GetPhysicalDisplaySize()
    {
        Graphics g = Graphics.FromHwnd(IntPtr.Zero);
        IntPtr desktop = g.GetHdc();

        int physicalScreenHeight = GetDeviceCaps(desktop, (int)DeviceCap.Desktopvertres);
        int physicalScreenWidth = GetDeviceCaps(desktop, (int)DeviceCap.Desktophorzres);

        return new Size(physicalScreenWidth, physicalScreenHeight);
    }
}

UPD: System.Windows.SystemParameters.PrimaryScreenWidth uses GetSystemMetrics. https://github.com/dotnet/wpf/blob/main/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/SystemParameters.cs#L3080C5-L3080C5

[DllImport("user32.dll")]
public static extern int GetSystemMetrics(int nIndex);

public const int CM_CXSCREEN = 0; // Width
public const int CM_CYSCREEN = 1; // Height

But the documentation says it's the same.

The width of the screen of the primary display monitor, in pixels. This is the same value obtained by calling GetDeviceCaps as follows: GetDeviceCaps( hdcPrimaryMonitor, HORZRES).

Iviya
  • 1
  • 1
  • I suspect this approach will return incorrect (or rather: stub or pretend values) given how frequently GDI is sandboxed in WIndows lately... (e.g. when you run a program with high-DPI mode disabled, for example) – Dai Jul 12 '23 at 12:39
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 14 '23 at 16:54