Created
July 23, 2022 18:07
-
-
Save emoacht/d7946eda864edf916a90a49fc750f79b to your computer and use it in GitHub Desktop.
Get size of primary monitor by PowerShell. To get actual size under Per-Monitor DPI environment, run this method in PowerShell ISE.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add-Type @" | |
using System; | |
using System.Runtime.InteropServices; | |
public static class MonitorHelper | |
{ | |
[DllImport("User32.dll")] | |
public static extern IntPtr MonitorFromWindow( | |
IntPtr hwnd, | |
int dwFlags); | |
[DllImport("User32.dll")] | |
[return: MarshalAs(UnmanagedType.Bool)] | |
public static extern bool GetMonitorInfo( | |
IntPtr hMonitor, | |
ref MONITORINFO lpmi); | |
[StructLayout(LayoutKind.Sequential)] | |
public struct MONITORINFO | |
{ | |
public int cbSize; | |
public RECT rcMonitor; | |
public RECT rcWork; | |
public int dwFlags; | |
} | |
[StructLayout(LayoutKind.Sequential)] | |
public struct RECT | |
{ | |
public int left; | |
public int top; | |
public int right; | |
public int bottom; | |
} | |
public static bool GetPrimaryMonitorSize(out int width, out int height) | |
{ | |
var handle = MonitorFromWindow(IntPtr.Zero, 1); | |
var info = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() }; | |
if (GetMonitorInfo(handle, ref info)) | |
{ | |
var rect = info.rcMonitor; | |
width = rect.right - rect.left; | |
height = rect.bottom - rect.top; | |
return true; | |
} | |
width = 0; | |
height = 0; | |
return false; | |
} | |
} | |
"@ | |
# To get actual size under Per-Monitor DPI environment, run this method in PowerShell ISE. | |
[int] $width = 0; | |
[int] $height = 0; | |
[MonitorHelper]::GetPrimaryMonitorSize([ref] $width, [ref] $height) | |
$width | |
$height | |
Pause |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment