制作一个盒子菜单如何为选择着色/突出显示?

问题描述

因此,我拼凑了一个包含标题和选项的菜单。使用箭头键选择一个项目。我想突出显示选中的项目,以便您可以告诉您当前正在选择的项目。我是PowerShell的新手,并且熟悉如何使用write-host更改颜色,但是在此示例中我一无所知。我认为我需要向其中插入颜色选项的那一行是以$ Width开头的那一行。我真的很感谢一些见识!这是我开始添加实际代码之前的最后一次打!!


    Function Create-Menu (){
    
    Param(
        [Parameter(Mandatory=$True)][String]$MenuTitle,[Parameter(Mandatory=$True)][array]$MenuOptions
    )

    $MaxValue = $MenuOptions.count-1
    $Selection = 0
    $EnterPressed = $False
    
    Clear-Host

    While($EnterPressed -eq $False){

        For ($i=0; $i -le $MaxValue; $i++){
            
    $Width = if($Title){$Length = $Title.Length;$Length2 = $MenuOptions|%{$_.length}|Sort -Descending|Select -First 1;$Length2,$Length|Sort -Descending|Select -First 1}else{$MenuOptions|%{$_.length}|Sort -Descending|Select -First 1}
    $Buffer = if(($Width*1.5) -gt 78){(78-$width)/2}else{$width/4}
    if($Buffer -gt 6){$Buffer = 6}
    $MaxWidth = $Buffer*2+$Width+$($MenuOptions.count).length
    $Menu = @()
    $Menu += "╔"+"═"*$maxwidth+"╗"
    if($MenuTitle){
        $Menu += "║"+" "*[Math]::Floor(($maxwidth-$MenuTitle.Length)/2)+$MenuTitle+" "*[Math]::Ceiling(($maxwidth-$MenuTitle.Length)/2)+"║"
        $Menu += "╟"+"─"*$maxwidth+"╢"
    }
    For($i=1;$i -le $MenuOptions.count;$i++){
        $Item = "$i`. "
        $Menu += "║"+" "*$Buffer+$Item+$MenuOptions[$i-1]+" "*($MaxWidth-$Buffer-$Item.Length-$MenuOptions[$i-1].Length)+"║"
    }
    $Menu += "╚"+"═"*$maxwidth+"╝"
    $menu
}

        $KeyInput = $host.ui.rawui.readkey("NoEcho,IncludeKeyDown").virtualkeycode

        Switch($KeyInput){
            13{
                $EnterPressed = $True
                $script:Selection = "$Selection"
                Clear-Host
                break
            }

            38{
                If ($Selection -eq 0){
                    $Selection = $MaxValue
                } Else {
                    $Selection -= 1
                }
                Clear-Host
                break
            }

            40{
                If ($Selection -eq $MaxValue){
                    $Selection = 0
                } Else {
                    $Selection +=1
                }
                Clear-Host
                break
            }
            Default{
                Clear-Host
            }
        }
    }
}

#MainMenu
Function MainMenu (){
Create-Menu -MenuTitle "Tool" -MenuOptions "Lookup","Prep","Tools","Settings","Cleanup and Exit"
If($script:Selection -eq 0) {Lookup}
If($script:Selection -eq 1) {PrepMenu} 
If($script:Selection -eq 2) {ToolsMenu} 
If($script:Selection -eq 3) {SettingsMenu} 
If($script:Selection -eq 4) {CleanupAndExit} 
}

MainMenu

pause

代码输出以下内容:

╔═════════════════════════╗
║          Tool           ║
╟─────────────────────────╢
║    1. Lookup            ║
║    2. Prep              ║
║    3. Tools             ║
║    4. Settings          ║
║    5. Cleanup and Exit  ║
╚═════════════════════════╝

解决方法

您可以在代码中进行一些较小的调整来添加颜色(我使用的是绿色,但是这取决于您)

function Create-Menu {
    Param(
        [Parameter(Mandatory=$True)][String]$MenuTitle,[Parameter(Mandatory=$True)][array]$MenuOptions
    )

    # test if we're not running in the ISE
    if ($Host.Name -match 'ISE') {
        Throw "This menu must be run in PowerShell Console"
    }

    $MaxValue = $MenuOptions.Count-1
    $Selection = 0
    $EnterPressed = $False

    While(!$EnterPressed) {
        # draw the menu
        Clear-Host
        for ($i = 0; $i -le $MaxValue; $i++){
            [int]$Width = [math]::Max($MenuTitle.Length,($MenuOptions | Measure-Object -Property Length -Maximum).Maximum)
            [int]$Buffer = if (($Width * 1.5) -gt 78) { (78 - $width) / 2 } else { $width / 4 }
            $Buffer = [math]::Min(6,$Buffer)
            $MaxWidth = $Buffer * 2 + $Width + $MenuOptions.Count.ToString().Length
            Write-Host ("╔" + "═" * $maxwidth + "╗")
            # write the title if present
            if (!([string]::IsNullOrWhiteSpace($MenuTitle))) {
                $leftSpace  = ' ' * [Math]::Floor(($maxwidth - $MenuTitle.Length)/2)
                $rightSpace = ' ' * [Math]::Ceiling(($maxwidth - $MenuTitle.Length)/2)
                Write-Host ("║" + $leftSpace + $MenuTitle + $rightSpace + "║")
                Write-Host ("╟" + "─" * $maxwidth + "╢")
            }
            # write the menu option lines
            for($i = 0; $i -lt $MenuOptions.Count; $i++){
                $Item = "$($i + 1). "
                $Option = $MenuOptions[$i]
                $leftSpace  = ' ' * $Buffer
                $rightSpace = ' ' * ($MaxWidth - $Buffer - $Item.Length - $Option.Length)
                $line = "║" + $leftSpace + $Item + $Option + $rightSpace + "║"
                if ($Selection -eq $i) {
                    Write-Host $line -ForegroundColor Green
                }
                else {
                    Write-Host $line
                }
            }
            Write-Host ("╚" + "═" * $maxwidth + "╝")
        }
        # wait for an accepted key press
        do {
            $KeyInput = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown').VirtualKeyCode
        } while (13,38,40 -notcontains $KeyInput)


        Switch($KeyInput){
            13{
                $EnterPressed = $True
                return $Selection
            }
            38 {
                $Selection--
                if ($Selection -lt 0){ $Selection = $MaxValue }
                break
            }
            40 { 
                $Selection++
                if ($Selection -gt $MaxValue) { $Selection = 0 }
                # or:    $Selection = ($Selection + 1) % ($MaxValue + 1)
                break
            }
        }
    }
}

#MainMenu
function MainMenu {
    $selected = Create-Menu -MenuTitle "Tools" -MenuOptions "Lookup","Prep","Tools","Settings","Cleanup and Exit"
    switch ($selected) {
        0 {"Lookup"}
        1 {"PrepMenu"}
        2 {"ToolsMenu"}
        3 {"SettingsMenu"}
        4 {"CleanupAndExit"}
    }
}

MainMenu

修改

仅出于乐趣,上面的代码在每次重画菜单之前都使用Clear-Host,这会导致菜单可行但闪烁。
在同一菜单下,但是这次重新绘制而没有先清除控制台窗口,从而使菜单更加平滑。

function Create-Menu {
    Param(
        [Parameter(Mandatory=$false)][string]  $MenuTitle = $null,[Parameter(Mandatory=$true)] [string[]]$MenuOptions
    )

    # test if we're not running in the ISE
    if ($Host.Name -match 'ISE') {
        Throw "This menu must be run in PowerShell Console"
    }

    $MaxValue = $MenuOptions.Count-1
    $Selection = 0
    $EnterPressed = $False
    [console]::CursorVisible = $false  # prevents cursor flickering
    Clear-Host

    while(!$EnterPressed) {
        # draw the menu without Clear-Host to prevent flicker
        [console]::SetCursorPosition(0,0)
        for ($i = 0; $i -le $MaxValue; $i++){
            [int]$Width = [math]::Max($MenuTitle.Length,40 -notcontains $KeyInput)


        Switch($KeyInput){
            13{
                $EnterPressed = $True
                [console]::CursorVisible = $true  # reset the cursors visibility
                return $Selection
            }
            38 {
                $Selection--
                if ($Selection -lt 0){ $Selection = $MaxValue }
                break
            }
            40 { 
                $Selection++
                if ($Selection -gt $MaxValue) { $Selection = 0 }
                # or:    $Selection = ($Selection + 1) % ($MaxValue + 1)
                break
            }
        }
    }
}

#MainMenu
function MainMenu {
    $selected = Create-Menu -MenuTitle "Tools" -MenuOptions "Lookup","Cleanup and Exit"
    switch ($selected) {
        0 {"Lookup"}
        1 {"PrepMenu"}
        2 {"ToolsMenu"}
        3 {"SettingsMenu"}
        4 {"CleanupAndExit"}
    }
}

MainMenu

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...