PowerShell рассчитать высоту пикселя панели запуска - PullRequest
0 голосов
/ 28 января 2020

Я хочу разместить windows на моем экране в разных позициях. Я могу рассчитать размеры экрана, как показано ниже (это массивы, если есть настройки для нескольких дисплеев):

$widths = (Get-WmiObject -Class Win32_DesktopMonitor | Select-Object ScreenWidth).ScreenWidth
$heights = (Get-WmiObject -Class Win32_DesktopMonitor | Select-Object ScreenHeight).ScreenHeight

Чтобы правильно разместить windows, мне также необходимо рассчитать высоту панели запуска. Кто-нибудь знает, как программно собрать высоту панели запуска с помощью PowerShell?

Я также хотел бы знать, как рассчитать позицию панели запуска (чтобы я знал, если она размещена вверху, внизу, слева, справа от экрана) если возможно?

Ответы [ 2 ]

1 голос
/ 29 января 2020

Вместо того, чтобы использовать WMI, вы должны быть в безопасности, используя $Screen.WorkingArea, который вы можете получить, используя, например, [System.Windows.Forms.Screen]::PrimaryScreen.

Сказав, что нижеприведенная функция получит вам размеры и положение панели задач. для определенного экрана:

Add-Type -AssemblyName System.Windows.Forms

function Get-TaskBarDimensions {
    param (
        [System.Windows.Forms.Screen]$Screen = [System.Windows.Forms.Screen]::PrimaryScreen
    )        

    $device = ($Screen.DeviceName -split '\\')[-1]
    if ($Screen.Primary) { $device += ' (Primary Screen)' }

    if ($Screen.Bounds.Equals($Screen.WorkingArea)) {
        Write-Warning "Taskbar is hidden on device $device or moved to another screen."
        return
    }


    # calculate heights and widths for the possible positions (left, top, right and bottom)
    $ScreenRect  = $Screen.Bounds
    $workingArea = $Screen.WorkingArea
    $left        = [Math]::Abs([Math]::Abs($ScreenRect.Left) - [Math]::Abs($WorkingArea.Left))
    $top         = [Math]::Abs([Math]::Abs($ScreenRect.Top) - [Math]::Abs($workingArea.Top))
    $right       = ($ScreenRect.Width - $left) - $workingArea.Width
    $bottom      = ($ScreenRect.Height - $top) - $workingArea.Height

    if ($bottom -gt 0) {
        # TaskBar is docked to the bottom
        return [PsCustomObject]@{
            X        = $workingArea.Left
            Y        = $workingArea.Bottom
            Width    = $workingArea.Width
            Height   = $bottom
            Position = 'Bottom'
            Device   = $device
        }
    }
    if ($left -gt 0) {
        # TaskBar is docked to the left
        return [PsCustomObject]@{
            X        = $ScreenRect.Left
            Y        = $ScreenRect.Top
            Width    = $left
            Height   = $ScreenRect.Height
            Position = 'Left'
            Device   = $device
        }
    }
    if ($top -gt 0) {
        # TaskBar is docked to the top
        return [PsCustomObject]@{
            X        = $workingArea.Left
            Y        = $ScreenRect.Top
            Width    = $workingArea.Width
            Height   = $top
            Position = 'Top'
            Device   = $device
        }
    }
    if ($right -gt 0) {
        # TaskBar is docked to the right
        return [PsCustomObject]@{
            X        = $workingArea.Right
            Y        = $ScreenRect.Top
            Width    = $right
            Height   = $ScreenRect.Height
            Position = 'Right'
            Device   = $device
        }
    }
}

Чтобы получить размеры панели задач только для основного экрана:

Get-TaskBarDimensions

Чтобы получить размеры панели задач для всех подключенных экранов:

[System.Windows.Forms.Screen]::AllScreens | ForEach-Object {
    Get-TaskBarDimensions $_
}

Это вернет объект со следующими свойствами:

X        : 0
Y        : 1160
Width    : 1920
Height   : 40
Position : Bottom
Device   : DISPLAY1 (Primary Screen)

Или - в случае, если панель задач скрыта или отсутствует на этом экране - предупреждение типа:

Панель задач скрыта на устройстве DISPLAY2 или перемещена на другой экран.

0 голосов
/ 09 марта 2020

Чтобы поделиться информацией, которую @Theo дал мне выше, я хотел создать функцию, которая могла бы позиционировать консоли PowerShell. Это в настоящее время не справляется с настройками нескольких мониторов (если кто-то хочет расширить функциональность до этого, я был бы рад видеть это!).

Я сохраняю их как lll и rrr и fff («полный размер») для быстрого доступа и сохранения их в моем Custom-Tools модуле, который доступен для всех моих сеансов консоли. fff основан на методе $host.UI.RawUI, который не так точен, как установка ConsolePosition (я обрезаю 1 символ с высоты, так как иногда он не подходит таким образом), но я очень доволен возможностью переключения настроек консоли очень легко таким образом.

function Global:Set-ConsolePosition ($x, $y, $w, $h) {
    # Note: the DLL code below should not be indented from the left-side
    Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")] 
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int W, int H); '
    # Do the Add-Type outside of the function as repeating it in a session can cause errors
    $consoleHWND = [Console.Window]::GetConsoleWindow();
    $consoleHWND = [Console.Window]::MoveWindow($consoleHWND, $x, $y, $w, $h);
    # $consoleHWND = [Console.Window]::MoveWindow($consoleHWND,75,0,600,600);
    # $consoleHWND = [Console.Window]::MoveWindow($consoleHWND,-6,0,600,600);
}
function lll {
    Add-Type -AssemblyName System.Windows.Forms
    $Screen = [System.Windows.Forms.Screen]::PrimaryScreen
    $width = $Screen.WorkingArea.Width   # .WorkingArea ignores the taskbar, .Bounds is whole screen
    $height = $Screen.WorkingArea.Height
    $w = $width/2 + 13
    $h = $height + 8
    $x = -7
    $y = 0
    Set-ConsolePosition $x $y $w $h

    $MyBuffer = $Host.UI.RawUI.BufferSize
    $MyWindow = $Host.UI.RawUI.WindowSize
    $MyBuffer.Height = 9999
    "`nWindowSize $($MyWindow.Width)x$($MyWindow.Height) (Buffer $($MyBuffer.Width)x$($MyBuffer.Height))"
    "Position : Left:$x Top:$y Width:$w Height:$h`n"
}
function rrr {
    Add-Type -AssemblyName System.Windows.Forms
    $Screen = [System.Windows.Forms.Screen]::PrimaryScreen
    $width = $Screen.WorkingArea.Width   # .WorkingArea ignores the taskbar, .Bounds is whole screen
    $height = $Screen.WorkingArea.Height
    $w = $width/2 + 13
    $h = $height + 8
    $x = $w - 20
    $y = 0
    Set-ConsolePosition $x $y $w $h

    $MyBuffer = $Host.UI.RawUI.BufferSize
    $MyWindow = $Host.UI.RawUI.WindowSize
    $MyBuffer.Height = 9999
    "`nWindowSize $($MyWindow.Width)x$($MyWindow.Height) (Buffer $($MyBuffer.Width)x$($MyBuffer.Height))"
    "Position : Left:$x Top:$y Width:$w Height:$h`n"
}
function fff {
    Set-ConsolePosition -7 0 600 600
    if ($Host.Name -match "console") {
        $MaxHeight = $host.UI.RawUI.MaxPhysicalWindowSize.Height - 1
        $MaxWidth = $host.UI.RawUI.MaxPhysicalWindowSize.Width
        $MyBuffer = $Host.UI.RawUI.BufferSize
        $MyWindow = $Host.UI.RawUI.WindowSize
        $MyWindow.Height = $MaxHeight
        $MyWindow.Width = $Maxwidth
        $MyBuffer.Height = 9999
        $MyBuffer.Width = $Maxwidth
        # $host.UI.RawUI.set_bufferSize($MyBuffer)
        # $host.UI.RawUI.set_windowSize($MyWindow)
        $host.UI.RawUI.BufferSize = $MyBuffer
        $host.UI.RawUI.WindowSize = $MyWindow
        "`nWindowSize $($MyWindow.Width)x$($MyWindow.Height) (Buffer $($MyBuffer.Width)x$($MyBuffer.Height))`n"
    }
}
...