我已经构建了一个菜单,但我想将其格式化为如下所示:
菜单标题位于框中,选项位于框中。
我找到了来自的盒子字符http://en.wikipedia.org/wiki/Box-drawing_character http://en.wikipedia.org/wiki/Box-drawing_character
╔═╗
║║
╚═╝
我想使用字符串的长度属性来绘制水平框线。
我意识到这已经很旧了,但似乎有很多来自志同道合的人的流量,他们想要比这更好的菜单选项System.Management.Automation.Host.ChoiceDescription
。我正在寻找类似的东西并发现这个封闭式问题 https://stackoverflow.com/questions/17576015/powershell-menu-selection-like-grub-curses-etc这启发我编写了一个菜单系统,该系统用一个适合最长选择长度或菜单标题的框包围着选项:
┌Choose an option┐
│first │
│second option │
│third │
└────────────────┘
该脚本仅适用于 Powershell 控制台,不适用于 ISE。使用箭头键将以反白方式突出显示所选内容。按 Enter 键将返回它。
function Show-SimpleMenu ([array]$MenuOptions, [string]$Title ='Choose an option'){
$maxLength = ($MenuOptions | Measure-Object -Maximum -Property Length).Maximum #get longest string length
If($maxLength -lt $Title.Length){$maxLength = $Title.Length}
$highlighted = 0
$MenuTop = [Console]::CursorTop
Do{
[Console]::CursorTop = $MenuTop
Write-Host "┌$($Title.PadRight($maxLength,'─'))┐"
for ($i = 0; $i -lt $MenuOptions.Length;$i++) {
Write-Host "│" -NoNewLine
if ($i -eq $highlighted) {
Write-Host "$(([string]$MenuOptions[$i]).PadRight($maxLength,' '))" -fore $host.UI.RawUI.BackgroundColor -back $host.UI.RawUI.ForegroundColor -NoNewline
} else {
Write-Host "$(([string]$MenuOptions[$i]).PadRight($maxLength,' '))" -fore $host.UI.RawUI.ForegroundColor -back $host.UI.RawUI.BackgroundColor -NoNewline
}
Write-Host "│"
}
Write-Host "└$('─' * ($maxLength))┘"
$keycode = [Console]::ReadKey($true)
If ($keyCode.Key -eq [ConsoleKey]::UpArrow -and $highlighted -gt 0 ) {$highlighted--}
If ($keycode.Key -eq [ConsoleKey]::DownArrow -and $highlighted -lt $MenuOptions.Length - 1) {$highlighted++}
}While($keyCode.Key -ne [ConsoleKey]::Enter -and $keycode.Key -ne [ConsoleKey]::Escape )
If($keyCode.Key -eq [ConsoleKey]::Enter){ $MenuOptions[$highlighted] }
}
Show-SimpleMenu @('first','second option','third')
还有一个GitHub 上的多选版本 https://github.com/mossrich/PowershellRecipes/blob/master/AsciiMenu.ps1允许使用空格键选择多个选项。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)