Search code examples
c#.netwinformsubuntumono

C# and Ubuntu - How do I get size of primary screen?


I'm trying to determine the size of my primary screen so I can capture its image. My setup is a laptop that has a 1600x900 display, and an external monitor that's 1920x1080. The code that gets the size runs fine on Windows, but gives the wrong result on Ubuntu (using MonoDevelop).

    Rectangle capture_rect = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
    Console.WriteLine("width={0} height={1}", capture_rect.Height, capture_rect.Width);

The result on Ubuntu is "width=3520 height=1080". If I disconnect the external monitor, I get the correct result, which is "width=1600 height=900". Any idea why I get the wrong value on Ubuntu with multiple displays?


Solution

  • Instead of using .NET to get the screen dimensions, I used Linux "xrandr". Here's my code:

    public Rectangle GetDisplaySize()
    {
        // Use xrandr to get size of screen located at offset (0,0).
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = "xrandr";
        p.Start();
        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();
        var match = System.Text.RegularExpressions.Regex.Match(output, @"(\d+)x(\d+)\+0\+0");
        var w = match.Groups[1].Value;
        var h = match.Groups[2].Value;
        Rectangle r = new Rectangle();
        r.Width = int.Parse(w);
        r.Height = int.Parse(h);
        Console.WriteLine ("Display Size is {0} x {1}", w, h);
        return r;
    }