4

#PSTip Working with the Windows.Forms.Screen Class

When working with Windows PowerShell it can be important to know the screen configuration and resolution of the current computer monitors. The System.Windows.Forms.Screen class provides this information for every monitor attached to this computer. In order to use this class the System.Windows.Forms.dll will be loaded first. After that we can view the AllScreens property of this class:

PS > Add-Type -AssemblyName System.Windows.Forms
PS > [System.Windows.Forms.Screen]::AllScreens

BitsPerPixel : 32
Bounds       : {X=0,Y=0,Width=1920,Height=1200}
DeviceName   : \\.\DISPLAY1
Primary      : True
WorkingArea  : {X=0,Y=0,Width=1920,Height=1160}

BitsPerPixel : 32
Bounds       : {X=1920,Y=0,Width=1920,Height=1200}
DeviceName   : \\.\DISPLAY2
Primary      : False
WorkingArea  : {X=1920,Y=0,Width=1858,Height=1200}

This information can be especially handy when working with Windows Forms as it gives insight into how a desktop is configured and base the location or size of a form based on this information. Another use can be to determine where the taskbar is located.

[System.Windows.Forms.Screen]::AllScreens | ForEach-Object {
    if ($_.Bounds.Width -ne $_.WorkingArea.Width) {
        "Taskbar is placed in vertical position on $($_.DeviceName)"
    } elseif ($_.Bounds.Height -ne $_.WorkingArea.Height) {
        "Taskbar is placed in horizontal position on $($_.DeviceName)"
    } else {
        "Taskbar is not visible on $($_.DeviceName)"
    }
}

Taskbar is placed in horizontal position on \\.\DISPLAY1
Taskbar is placed in vertical position on \\.\DISPLAY2
Filed in: Columns, Tips and Tricks Tags: , , ,

4 Responses to "#PSTip Working with the Windows.Forms.Screen Class"

  1. Other says:

    What are your thoughts on building GUIs with PowerShell. Some people say that if you want a GUI use C# or an HTA. Are PowerShell GUIs ok to use, or are they not part of the “best practices?”

    • ShayLevy says:

      Windows.Forms is used by C# or PowerShell to build graphical user interfaces, I don’t see any reason why not to use them. Another option would be to use WPF.

    • Jaap Brasser says:

      I only build scripts with a GUI when purposely building something that will be used by people not fluent in PowerShell. I feel PowerShell is totally capable to be used as a GUI, PowerShell Studio 2012 by Sapien provides a nice tool to build user interfaces. You could pick up the trial version if you want to experiment with it.

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: