DevicesPrintersTUI.ps1
|
<#PSScriptInfo .VERSION 1.0.9 .GUID a4d2c8fb-9b2f-410a-ba92-f04b1236ea2f .AUTHOR Robert .COMPANYNAME OAOA-DEV .COPYRIGHT .TAGS Big TUI Tools PowerShellToolkit .LICENSEURI .PROJECTURI https://oaoa.dev/tools .ICONURI .EXTERNALMODULEDEPENDENCIES .REQUIREDMODULES .EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES .PRIVATEDATA .DESCRIPTION A console TUI application for Windows Devices and Printers. #> <# .SYNOPSIS Provides a text user interface (TUI) inside the PowerShell console to view devices and printers for a selected user profile. .DESCRIPTION A console TUI application for Windows Devices and Printers. .PARAMETER None .EXAMPLE DevicesPrintersTUI #> # --- TUI LAYOUT ENGINE MODULE FUNCTIONS --- # Generic Reusable PowerShell Console TUI Library # Author: Antigravity $ESC = [char]27 # Global Layout Variables (defaults, dynamically updated on resize) $global:leftWidth = 35 # mainHeight will be dynamically updated $global:mainHeight = 25 # ANSI Color Utilities function Get-ANSIColor($name) { switch ($name) { 'Reset' { "$ESC[0m" } 'Bold' { "$ESC[1m" } 'Inverse' { "$ESC[7m" } 'SelectedActive' { "$ESC[37;44m" } # White on Blue 'SelectedInactive' { "$ESC[37;100m" } # White on Dark Gray 'Error' { "$ESC[91m" } # Bright Red 'Warning' { "$ESC[93m" } # Bright Yellow 'Info' { "$ESC[92m" } # Bright Green 'Gray' { "$ESC[90m" } # Dark Gray 'White' { "$ESC[97m" } # White 'Cyan' { "$ESC[96m" } # Cyan 'Blue' { "$ESC[94m" } # Blue 'Header' { "$ESC[30;47m" } # Black on Light Gray 'ErrorRow' { "$ESC[37;41m" } # White on Red background 'WarningRow' { "$ESC[30;43m" } # Black on Yellow background 'GreenRow' { "$ESC[32m" } # Green text default { "$ESC[0m" } } } # Position the cursor function Set-Cursor($x, $y) { [Console]::SetCursorPosition($x, $y) } # Write text at specific coordinates function Write-At($x, $y, $text, $colorName = 'Reset') { $color = Get-ANSIColor $colorName $reset = Get-ANSIColor 'Reset' Set-Cursor $x $y [Console]::Write("$color$text$reset") } # Initialize console settings for TUI function Initialize-Console { $global:originalCursorVisible = [Console]::CursorVisible $global:originalOutputEncoding = [Console]::OutputEncoding [Console]::CursorVisible = $false [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 # Enter Alternate Screen Buffer to preserve user scrollback [Console]::Write("$ESC[?1049h") [Console]::Write("$ESC[?25l") # ANSI Hide Cursor [Console]::Write("$ESC[2J") # Clear entire screen } # Restore original console settings on exit function Restore-Console { # Exit Alternate Screen Buffer [Console]::Write("$ESC[?1049l") [Console]::Write("$ESC[?25h") # ANSI Show Cursor [Console]::CursorVisible = $global:originalCursorVisible [Console]::OutputEncoding = $global:originalOutputEncoding } # Generic Borders Drawing function Draw-Borders { param( [int]$Width, [int]$Height, [int]$LeftWidth, [int]$MainHeight, [int]$FocusArea, [string]$LeftTitle = "", [string]$RightTopTitle = "", [string]$RightBottomTitle = "", [bool]$HasVerticalDivider = $true, [bool]$HasHorizontalDivider = $true, [double]$RightTopWidthPercent = 1.0 ) $rightWidth = $Width - $LeftWidth - 4 # 1. Draw top border $topBorder = "┌" + ("─" * $LeftWidth) + $(if ($HasVerticalDivider) { "┬" } else { "─" }) + ("─" * $rightWidth) + "┐" Write-At 0 1 $topBorder 'Gray' # 2. Draw middle lines for ($y = 2; $y -le ($Height - 3); $y++) { Write-At 0 $y "│" 'Gray' if ($HasVerticalDivider) { Write-At ($LeftWidth + 1) $y "│" 'Gray' } Write-At ($Width - 2) $y "│" 'Gray' } # 3. Draw horizontal divider between Table and Details (right side only, if exists) if ($HasHorizontalDivider) { $dividerStart = if ($HasVerticalDivider) { $LeftWidth + 1 } else { 0 } $rightDivider = $(if ($HasVerticalDivider) { "├" } else { "│" }) + ("─" * $rightWidth) + "┤" Write-At $dividerStart ($MainHeight + 1) $rightDivider 'Gray' } # 4. Draw bottom border $bottomBorder = "└" + ("─" * $LeftWidth) + $(if ($HasVerticalDivider) { "┴" } else { "─" }) + ("─" * $rightWidth) + "┘" Write-At 0 ($Height - 2) $bottomBorder 'Gray' # 5. Draw secondary vertical divider if RightTopWidthPercent is < 1.0 (for Resource Monitor graph) if ($HasVerticalDivider -and $RightTopWidthPercent -lt 1.0 -and $RightTopWidthPercent -gt 0.0) { $listWidth = [int]($rightWidth * $RightTopWidthPercent) $dividerX = $LeftWidth + 2 + $listWidth for ($y = 2; $y -le $MainHeight; $y++) { Write-At $dividerX $y "│" 'Gray' } Write-At $dividerX 1 "┬" 'Gray' if ($HasHorizontalDivider) { Write-At $dividerX ($MainHeight + 1) "┴" 'Gray' } } # 6. Draw highlighted titles to indicate focus if ($LeftTitle) { $lTitleText = if ($FocusArea -eq 0) { "● $LeftTitle ●" } else { " $LeftTitle " } $lTitleX = [int](($LeftWidth - $lTitleText.Length) / 2) + 1 $lColor = if ($FocusArea -eq 0) { 'SelectedActive' } else { 'Header' } Write-At $lTitleX 1 $lTitleText $lColor } if ($RightTopTitle) { $rtTitleText = if ($FocusArea -eq 1) { "● $RightTopTitle ●" } else { " $RightTopTitle " } $rtWidth = if ($RightTopWidthPercent -lt 1.0) { [int]($rightWidth * $RightTopWidthPercent) } else { $rightWidth } $rtTitleX = $LeftWidth + 2 + [int](($rtWidth - $rtTitleText.Length) / 2) $rtColor = if ($FocusArea -eq 1) { 'SelectedActive' } else { 'Header' } Write-At $rtTitleX 1 $rtTitleText $rtColor } if ($RightBottomTitle -and $HasHorizontalDivider) { $rbTitleText = if ($FocusArea -eq 2) { "● $RightBottomTitle ●" } else { " $RightBottomTitle " } $rbTitleX = $LeftWidth + 2 + [int](($rightWidth - $rbTitleText.Length) / 2) $rbColor = if ($FocusArea -eq 2) { 'SelectedActive' } else { 'Header' } Write-At $rbTitleX ($MainHeight + 1) $rbTitleText $rbColor } } # Generic Menu Bar Drawing function Draw-Menu { param( [int]$Width, [string[]]$Items ) $menuColor = Get-ANSIColor 'Header' $reset = Get-ANSIColor 'Reset' $menuText = " " + ($Items -join " ") $paddedMenu = $menuText.PadRight($Width).Substring(0, $Width) Set-Cursor 0 0 [Console]::Write("$menuColor$paddedMenu$reset") } # Generic Status Bar Drawing function Draw-Status { param( [string]$StatusText, [string]$FocusAreaText, [string]$HelpText, [int]$Width, [int]$Height ) $statusColor = Get-ANSIColor 'Header' $reset = Get-ANSIColor 'Reset' $focusPart = if ($FocusAreaText) { "[$FocusAreaText]" } else { "" } $helpPart = if ($HelpText) { $HelpText + " │ " } else { "" } $maxStatusLen = $Width - $focusPart.Length - $helpPart.Length - 10 $leftText = $StatusText if ($leftText.Length -gt $maxStatusLen) { $leftText = $leftText.Substring(0, $maxStatusLen - 3) + "..." } $paddedStatusText = " " + $helpPart + $leftText # Pad status bar to exactly Width - 2 to prevent console host auto-scroll $remainingSpaces = ($Width - 2) - $paddedStatusText.Length - $focusPart.Length if ($remainingSpaces -lt 0) { $remainingSpaces = 0 } $fullStatus = $paddedStatusText + (" " * $remainingSpaces) + $focusPart if ($fullStatus.Length -gt ($Width - 2)) { $fullStatus = $fullStatus.Substring(0, $Width - 2) } Set-Cursor 0 ($Height - 1) [Console]::Write("$statusColor$fullStatus$reset") } # Recalculate dimensions function Update-LayoutDimensions { param( [int]$Width, [int]$Height ) $global:mainHeight = $Height - 16 if ($global:mainHeight -lt 5) { $global:mainHeight = 5 } $global:leftWidth = 35 $maxWidth = [int]($Width * 0.4) if ($global:leftWidth -gt $maxWidth) { $global:leftWidth = $maxWidth } if ($global:leftWidth -lt 15) { $global:leftWidth = 15 } } # --- TREE VIEW COMPONENTS --- function Get-VisibleNodes($node) { $result = [System.Collections.ArrayList]::new() function Add-Node($n) { $result.Add($n) | Out-Null if (!$n.IsLeaf -and $n.IsExpanded -and $n.Children) { foreach ($child in $n.Children) { Add-Node $child } } } Add-Node $node return $result } function Draw-TreeView { param( [System.Collections.ArrayList]$VisibleNodes, [int]$SelectedIndex, [int]$ScrollOffset, [int]$LeftWidth, [int]$TreeHeight, [bool]$IsFocused = $true ) $startX = 1 $startY = 2 $reset = Get-ANSIColor 'Reset' for ($i = 0; $i -lt $TreeHeight; $i++) { $nodeIndex = $ScrollOffset + $i $y = $startY + $i if ($nodeIndex -lt $VisibleNodes.Count) { $node = $VisibleNodes[$nodeIndex] $prefix = if ($node.IsLeaf) { " " } else { if ($node.IsExpanded) { "- " } else { "+ " } } $indent = " " * ($node.Level + 1) $displayText = $indent + $prefix + $node.Label if ($displayText.Length -gt $LeftWidth) { $displayText = $displayText.Substring(0, $LeftWidth - 3) + "..." } $paddedText = $displayText.PadRight($LeftWidth) if ($nodeIndex -eq $SelectedIndex) { $color = if ($IsFocused) { Get-ANSIColor 'SelectedActive' } else { Get-ANSIColor 'SelectedInactive' } } else { $isDisabled = $false $isHidden = $false if ($node -is [System.Collections.IDictionary]) { if ($node.ContainsKey('IsDisabled')) { $isDisabled = $node['IsDisabled'] } if ($node.ContainsKey('IsHidden')) { $isHidden = $node['IsHidden'] } } else { try { $isDisabled = $node.IsDisabled } catch {} try { $isHidden = $node.IsHidden } catch {} } if ($isDisabled) { $color = Get-ANSIColor 'Error' } elseif ($isHidden) { $color = Get-ANSIColor 'Gray' } else { $color = Get-ANSIColor 'Reset' } } Write-At $startX $y $paddedText # Set highlight Set-Cursor $startX $y [Console]::Write("$color$paddedText$reset") } else { Write-At $startX $y (" " * $LeftWidth) } } } # --- GENERIC TABLE VIEW COMPONENTS --- # Helper to format bytes function Format-Bytes { param($bytes) if ($null -eq $bytes) { return "0 B" } try { $bytes = [double]$bytes } catch { return "0 B" } if ($bytes -ge 1GB) { return "{0:N2} GB" -f ($bytes / 1GB) } if ($bytes -ge 1MB) { return "{0:N2} MB" -f ($bytes / 1MB) } if ($bytes -ge 1KB) { return "{0:N2} KB" -f ($bytes / 1KB) } return "{0:N0} B" -f $bytes } # Helper to format date strings like "20260527" -> "2026-05-27" function Format-DateString { param($str) if ($null -eq $str -or $str.Length -ne 8) { return $str } return "$($str.Substring(0,4))-$($str.Substring(4,2))-$($str.Substring(6,2))" } # Draw generic table header function Draw-TableHeader { param( [int]$StartX, [int]$StartY, [array]$Columns, # @{ Label="Name"; Width=15; Align="Left" } [int]$Width ) $reset = Get-ANSIColor 'Reset' $headerColor = Get-ANSIColor 'Header' $headerParts = @() foreach ($col in $Columns) { $label = $col.Label $w = $col.Width if ($label.Length -gt $w) { $label = $label.Substring(0, $w) } $padded = if ($col.Align -eq 'Right') { $label.PadLeft($w) } else { $label.PadRight($w) } $headerParts += $padded } $headerText = $headerParts -join "│" $paddedHeader = $headerText.PadRight($Width).Substring(0, $Width) Set-Cursor $startX $startY [Console]::Write("$headerColor$paddedHeader$reset") } # Draw generic table rows function Draw-TableRows { param( [System.Collections.ArrayList]$Items, [int]$SelectedIndex, [int]$ScrollOffset, [array]$Columns, [int]$StartX, [int]$StartY, [int]$Width, [int]$Height, [bool]$IsFocused = $true, [scriptblock]$RowColorScript = $null ) $reset = Get-ANSIColor 'Reset' for ($i = 0; $i -lt $Height; $i++) { $itemIndex = $ScrollOffset + $i $y = $startY + $i if ($itemIndex -lt $Items.Count) { $item = $Items[$itemIndex] $rowParts = @() foreach ($col in $Columns) { $val = $null if ($null -ne $item) { if ($item -is [hashtable]) { $val = $item[$col.Prop] } else { $val = $item.$($col.Prop) } } if ($null -eq $val) { $val = "" } # Format cell values $formattedVal = switch ($col.Format) { 'Percent' { "{0:F1} %" -f $val } 'MB' { "{0:N1} MB" -f ($val / 1MB) } 'Bytes' { Format-Bytes $val } 'Decimal' { "{0:F1}" -f $val } 'DateTime' { if ($val -is [DateTime]) { $val.ToString("yyyy-MM-dd HH:mm:ss") } else { $val.ToString() } } 'RegistryDate'{ Format-DateString $val } default { $val.ToString() } } # Strip control characters to prevent cursor shifting $formattedVal = $formattedVal -replace "`r", "" -replace "`n", "" -replace "`t", " " $w = $col.Width if ($formattedVal.Length -gt $w) { $formattedVal = if ($w -gt 2) { $formattedVal.Substring(0, $w - 2) + ".." } else { $formattedVal.Substring(0, $w) } } $padded = if ($col.Align -eq 'Right') { $formattedVal.PadLeft($w) } else { $formattedVal.PadRight($w) } $rowParts += $padded } $rowText = $rowParts -join "│" # Select background based on active selection if ($itemIndex -eq $SelectedIndex) { $color = if ($IsFocused) { Get-ANSIColor 'SelectedActive' } else { Get-ANSIColor 'SelectedInactive' } } else { if ($null -ne $RowColorScript) { $colorName = & $RowColorScript $item $color = Get-ANSIColor $colorName } else { $color = Get-ANSIColor 'Reset' } } $paddedRow = $rowText.PadRight($Width).Substring(0, $Width) Set-Cursor $StartX $y [Console]::Write("$color$paddedRow$reset") } else { # Empty row Set-Cursor $StartX $y [Console]::Write(" " * $Width) } } } # --- DETAILS VIEW COMPONENTS --- function Get-DetailPropertyLine($lbl1, $val1, $lbl2, $val2, $colWidth) { $lblW = 12 $valW = $colWidth - $lblW if ($valW -lt 5) { $valW = 5 } $lbl1Str = $lbl1.PadRight($lblW).Substring(0, $lblW) $val1Str = if ($null -ne $val1) { $val1.ToString() } else { "" } if ($val1Str.Length -gt $valW) { $val1Str = $val1Str.Substring(0, $valW - 3) + "..." } $col1Text = ($lbl1Str + $val1Str).PadRight($colWidth) $lbl2Str = $lbl2.PadRight($lblW).Substring(0, $lblW) $val2Str = if ($null -ne $val2) { $val2.ToString() } else { "" } if ($val2Str.Length -gt $valW) { $val2Str = $val2Str.Substring(0, $valW - 3) + "..." } $col2Text = ($lbl2Str + $val2Str).PadRight($colWidth) return "$col1Text │ $col2Text" } # Wrap text lines helper function Wrap-Text($text, $maxLength) { if ([string]::IsNullOrEmpty($text)) { return @("") } $paragraphs = $text.Split(@("`r`n", "`n"), [System.StringSplitOptions]::None) $lines = [System.Collections.ArrayList]::new() foreach ($para in $paragraphs) { if ($para.Length -le $maxLength) { $lines.Add($para) | Out-Null continue } $words = $para.Split(' ') $currentLine = "" foreach ($word in $words) { if ($currentLine.Length -eq 0) { $currentLine = $word } elseif (($currentLine.Length + 1 + $word.Length) -le $maxLength) { $currentLine += " " + $word } else { $lines.Add($currentLine) | Out-Null $currentLine = $word } } if ($currentLine.Length -gt 0) { $lines.Add($currentLine) | Out-Null } } return $lines } function Draw-Details { param( [array]$HeaderLines, [array]$MessageLines, [int]$ScrollOffset, [int]$StartX, [int]$StartY, [int]$Width, [int]$Height ) $hasHeader = ($null -ne $HeaderLines -and $HeaderLines.Count -gt 0) if ($hasHeader) { # Draw the header lines (up to 4) $headerCount = $HeaderLines.Count for ($i = 0; $i -lt 4; $i++) { $y = $StartY + $i $lineText = if ($i -lt $headerCount) { $HeaderLines[$i] } else { "" } if ($lineText.Length -gt $Width) { $lineText = $lineText.Substring(0, $Width) } $lineText = $lineText -replace "`r", "" -replace "`n", "" -replace "`t", " " Set-Cursor $StartX $y [Console]::Write($lineText.PadRight($Width)) } # Draw divider line $yDivider = $StartY + 4 $reset = Get-ANSIColor 'Reset' $gray = Get-ANSIColor 'Gray' Set-Cursor $StartX $yDivider [Console]::Write("$gray" + ("─" * $Width) + "$reset") $scrollAreaHeight = $Height - 5 $bodyStartY = $StartY + 5 } else { $scrollAreaHeight = $Height $bodyStartY = $StartY } # Draw scrollable body message lines $messageCount = if ($null -eq $MessageLines) { 0 } else { $MessageLines.Count } for ($i = 0; $i -lt $scrollAreaHeight; $i++) { $lineIndex = $ScrollOffset + $i $y = $bodyStartY + $i $lineText = if ($lineIndex -lt $messageCount) { $MessageLines[$lineIndex] } else { "" } if ($lineText.Length -gt $Width) { $lineText = $lineText.Substring(0, $Width) } $lineText = $lineText -replace "`r", "" -replace "`n", "" -replace "`t", " " Set-Cursor $StartX $y [Console]::Write($lineText.PadRight($Width)) } # Fill remaining space for ($y = $bodyStartY + $scrollAreaHeight; $y -lt $StartY + $Height; $y++) { Set-Cursor $StartX $y [Console]::Write(" " * $Width) } } # --- TEXT DIALOG INPUT BOX --- function Show-InputBox { param( [string]$Prompt, [string]$Title, [int]$Width, [int]$Height ) $boxW = 60 $boxH = 5 $boxX = [int](($Width - $boxW) / 2) $boxY = [int](($Height - $boxH) / 2) $reset = Get-ANSIColor 'Reset' $borderC = Get-ANSIColor 'White' $titleC = Get-ANSIColor 'SelectedActive' # 1. Draw outer frames of the box $topB = "╔" + ("═" * ($boxW - 2)) + "╗" $midB = "║" + (" " * ($boxW - 2)) + "║" $botB = "╚" + ("═" * ($boxW - 2)) + "╝" Write-At $boxX $boxY $topB 'White' Write-At $boxX ($boxY + 1) $midB 'White' Write-At $boxX ($boxY + 2) $midB 'White' Write-At $boxX ($boxY + 3) $midB 'White' Write-At $boxX ($boxY + 4) $botB 'White' # Draw title $titleText = " $Title " $titleX = $boxX + [int](($boxW - $titleText.Length) / 2) Write-At $titleX $boxY $titleText 'SelectedActive' # Draw prompt text Write-At ($boxX + 2) ($boxY + 1) $Prompt $inputText = "" $inputX = $boxX + 2 $inputY = $boxY + 2 $maxInputLen = $boxW - 4 # Temporarily show cursor [Console]::Write("$ESC[?25h") [Console]::CursorVisible = $true while ($true) { # Render current text Set-Cursor $inputX $inputY $displayText = $inputText if ($displayText.Length -gt $maxInputLen) { $displayText = "..." + $displayText.Substring($displayText.Length - $maxInputLen + 3) } [Console]::Write($displayText.PadRight($maxInputLen)) $cursorX = $inputX + [Math]::Min($displayText.Length, $maxInputLen) Set-Cursor $cursorX $inputY $key = [Console]::ReadKey($true) if ($key.Key -eq 'Enter') { break } if ($key.Key -eq 'Escape') { $inputText = $null break } if ($key.Key -eq 'Backspace') { if ($inputText.Length -gt 0) { $inputText = $inputText.Substring(0, $inputText.Length - 1) } } else { if ($key.KeyChar -ge 32 -and $key.KeyChar -le 126) { $inputText += $key.KeyChar } } } [Console]::Write("$ESC[?25l") [Console]::CursorVisible = $false return $inputText } # --- SCROLLABLE CHECKLIST DIALOG WITH SEARCH FILTERING --- function Show-CheckListDialog { param( [string]$Prompt, [string]$Title, [System.Collections.ArrayList]$Items, # Array of @{ Label = 'Name'; Checked = $true/$false } [int]$Width, [int]$Height, [switch]$ReadOnly, [switch]$HideSearch ) $boxW = 80 if ($boxW -gt ($Width - 4)) { $boxW = $Width - 4 } if ($boxW -lt 40) { $boxW = 40 } $boxH = 18 $boxX = [int](($Width - $boxW) / 2) if ($boxX -lt 0) { $boxX = 0 } $boxY = [int](($Height - $boxH) / 2) if ($boxY -lt 1) { $boxY = 1 } $reset = Get-ANSIColor 'Reset' $topB = "╔" + ("═" * ($boxW - 2)) + "╗" $midB = "║" + (" " * ($boxW - 2)) + "║" $botB = "╚" + ("═" * ($boxW - 2)) + "╝" $searchQuery = "" $selectedIndex = 0 $scrollOffset = 0 $listHeight = if ($HideSearch) { $boxH - 5 } else { $boxH - 8 } $focusedControl = if ($HideSearch) { 'List' } else { 'Search' } while ($true) { # 1. Draw outer frame Write-At $boxX $boxY $topB 'White' for ($i = 1; $i -lt ($boxH - 1); $i++) { Write-At $boxX ($boxY + $i) $midB 'White' } Write-At $boxX ($boxY + $boxH - 1) $botB 'White' # Title $titleText = " $Title " $titleX = $boxX + [int](($boxW - $titleText.Length) / 2) Write-At $titleX $boxY $titleText 'SelectedActive' # Prompt Write-At ($boxX + 2) ($boxY + 1) $Prompt if (-not $HideSearch) { # Search Box label and input field $searchLabel = "Search Filter: " $inputW = $boxW - 22 if ($inputW -lt 10) { $inputW = 10 } $dispQuery = $searchQuery if ($dispQuery.Length -gt ($inputW - 2)) { $dispQuery = $dispQuery.Substring($dispQuery.Length - ($inputW - 2)) } if ($focusedControl -eq 'Search') { Write-At ($boxX + 2) ($boxY + 2) $searchLabel 'White' $fieldVal = " $dispQuery" + "_" $fieldVal = $fieldVal.PadRight($inputW) Write-At ($boxX + 17) ($boxY + 2) $fieldVal 'SelectedActive' } else { Write-At ($boxX + 2) ($boxY + 2) $searchLabel 'Gray' $fieldVal = " $dispQuery" $fieldVal = $fieldVal.PadRight($inputW) Write-At ($boxX + 17) ($boxY + 2) $fieldVal 'SelectedInactive' } Write-At ($boxX + 2) ($boxY + 3) ("─" * ($boxW - 4)) 'Gray' } # Filter items based on search query $filteredItems = [System.Collections.ArrayList]::new() foreach ($item in $Items) { if ([string]::IsNullOrEmpty($searchQuery) -or $item.Label.IndexOf($searchQuery, [System.StringComparison]::OrdinalIgnoreCase) -ge 0) { $filteredItems.Add($item) | Out-Null } } # Bounds check if ($selectedIndex -ge $filteredItems.Count) { $selectedIndex = [Math]::Max(0, $filteredItems.Count - 1) } if ($selectedIndex -lt 0) { $selectedIndex = 0 } if ($selectedIndex -lt $scrollOffset) { $scrollOffset = $selectedIndex } if ($selectedIndex -ge ($scrollOffset + $listHeight)) { $scrollOffset = $selectedIndex - $listHeight + 1 } if ($scrollOffset -lt 0) { $scrollOffset = 0 } # Draw Checklist items for ($i = 0; $i -lt $listHeight; $i++) { $itemIdx = $scrollOffset + $i $y = if ($HideSearch) { $boxY + 2 + $i } else { $boxY + 4 + $i } if ($itemIdx -lt $filteredItems.Count) { $item = $filteredItems[$itemIdx] $text = if ($ReadOnly) { " $($item.Label) " } else { $chk = if ($item.Checked) { "[x]" } else { "[ ]" } " $chk $($item.Label) " } if ($text.Length -gt ($boxW - 6)) { $text = $text.Substring(0, $boxW - 9) + "..." } $paddedText = $text.PadRight($boxW - 6) if ($itemIdx -eq $selectedIndex) { $colorName = if ($focusedControl -eq 'List') { 'SelectedActive' } else { 'SelectedInactive' } $color = Get-ANSIColor $colorName } else { $color = Get-ANSIColor 'Reset' } Set-Cursor ($boxX + 3) $y [Console]::Write("$color$paddedText$reset") } else { Write-At ($boxX + 3) $y (" " * ($boxW - 6)) } } Write-At ($boxX + 2) ($boxY + $boxH - 3) ("─" * ($boxW - 4)) 'Gray' # Show shortcut guidelines dynamically based on focus if ($focusedControl -eq 'Search') { $shortcuts = " [Tab] List | [Backspace] Delete | [Enter] OK | [Esc] Cancel" } else { $shortcutParts = @() if (-not $HideSearch) { $shortcutParts += "[Tab] Search" } if (-not $ReadOnly) { $shortcutParts += "[Space] Toggle" } $shortcutParts += "[Arrows] Move" $shortcutParts += "[Enter] OK" $shortcutParts += "[Esc] Cancel" $shortcuts = " " + ($shortcutParts -join " | ") } $paddedShortcuts = $shortcuts.PadRight($boxW - 4) Write-At ($boxX + 2) ($boxY + $boxH - 2) $paddedShortcuts 'Header' # Read Key $key = [Console]::ReadKey($true) if ($key.Key -eq 'Escape') { return $null } if ($key.Key -eq 'Enter') { return $Items } if ($key.Key -eq 'Tab') { if (-not $HideSearch) { if ($focusedControl -eq 'Search') { $focusedControl = 'List' } else { $focusedControl = 'Search' } } } elseif ($focusedControl -eq 'Search') { if ($key.Key -eq 'Backspace') { if ($searchQuery.Length -gt 0) { $searchQuery = $searchQuery.Substring(0, $searchQuery.Length - 1) $selectedIndex = 0 $scrollOffset = 0 } } elseif ($key.Key -eq 'Space') { $searchQuery += " " $selectedIndex = 0 $scrollOffset = 0 } else { if ($key.KeyChar -ge 32 -and $key.KeyChar -le 126) { $searchQuery += $key.KeyChar $selectedIndex = 0 $scrollOffset = 0 } } } elseif ($focusedControl -eq 'List') { if ($key.Key -eq 'Space') { if (-not $ReadOnly) { if ($filteredItems.Count -gt 0) { $selectedItem = $filteredItems[$selectedIndex] $selectedItem.Checked = -not $selectedItem.Checked } } } elseif ($key.Key -eq 'UpArrow') { if ($selectedIndex -gt 0) { $selectedIndex-- } } elseif ($key.Key -eq 'DownArrow') { if ($selectedIndex -lt ($filteredItems.Count - 1)) { $selectedIndex++ } } elseif ($key.Key -eq 'PageUp') { $selectedIndex = [Math]::Max(0, $selectedIndex - $listHeight) } elseif ($key.Key -eq 'PageDown') { $selectedIndex = [Math]::Min($filteredItems.Count - 1, $selectedIndex + $listHeight) } } } } # --- LIST SELECTION DIALOG (NO SEARCH) --- function Show-ListSelectionDialog { param( [string]$Prompt, [string]$Title, [System.Collections.ArrayList]$Items, # Array of strings or PSCustomObjects with a Label property [int]$SelectedIndex = 0, [int]$Width, [int]$Height ) $boxW = 50 $boxH = 6 + $Items.Count if ($boxH -lt 8) { $boxH = 8 } $boxX = [int]((($Width - $boxW) / 2)) $boxY = [int]((($Height - $boxH) / 2)) if ($boxX -lt 0) { $boxX = 0 } if ($boxY -lt 1) { $boxY = 1 } $reset = Get-ANSIColor 'Reset' while ($true) { # Draw outer frames of the box $topB = "╔" + ("═" * ($boxW - 2)) + "╗" $midB = "║" + (" " * ($boxW - 2)) + "║" $botB = "╚" + ("═" * ($boxW - 2)) + "╝" Write-At $boxX $boxY $topB 'White' for ($i = 1; $i -lt ($boxH - 1); $i++) { Write-At $boxX ($boxY + $i) $midB 'White' } Write-At $boxX ($boxY + $boxH - 1) $botB 'White' # Draw title $titleText = " $Title " $titleX = $boxX + [int](($boxW - $titleText.Length) / 2) Write-At $titleX $boxY $titleText 'SelectedActive' # Draw prompt text Write-At ($boxX + 2) ($boxY + 1) $Prompt Write-At ($boxX + 2) ($boxY + 2) ("─" * ($boxW - 4)) 'Gray' # Draw items for ($i = 0; $i -lt $Items.Count; $i++) { $item = $Items[$i] $itemLabel = if ($item -is [PSCustomObject] -or $item -is [hashtable]) { $item.Label } else { $item } $text = " $itemLabel " if ($text.Length -gt ($boxW - 6)) { $text = $text.Substring(0, $boxW - 9) + "..." } $paddedText = $text.PadRight($boxW - 6) $y = $boxY + 3 + $i if ($i -eq $SelectedIndex) { Write-At ($boxX + 3) $y $paddedText 'SelectedActive' } else { Write-At ($boxX + 3) $y $paddedText 'Reset' } } Write-At ($boxX + 2) ($boxY + $boxH - 3) ("─" * ($boxW - 4)) 'Gray' # Draw help bar at the bottom $shortcuts = " [Arrows] Move │ [Enter] Select │ [Esc] Cancel" $paddedShortcuts = $shortcuts.PadRight($boxW - 4) Write-At ($boxX + 2) ($boxY + $boxH - 2) $paddedShortcuts 'Header' $key = [Console]::ReadKey($true) if ($key.Key -eq 'Escape') { return $null } if ($key.Key -eq 'Enter') { return $SelectedIndex } if ($key.Key -eq 'UpArrow') { if ($SelectedIndex -gt 0) { $SelectedIndex-- } } elseif ($key.Key -eq 'DownArrow') { if ($SelectedIndex -lt ($Items.Count - 1)) { $SelectedIndex++ } } } } # Export functions # --- MAIN UTILITY DRIVER EXECUTION --- # PowerShell TUI Devices and Printers Main Driver # Run this script to start the Devices and Printers console interface. # Author: Antigravity $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path # --- PROMPT USER PROFILE SELECTION --- function Select-UserProfile($width, $height) { $hkuSids = Get-ChildItem Registry::HKEY_USERS -ErrorAction SilentlyContinue | Where-Object { $_.PSChildName -like 'S-1-5-21*' -and $_.PSChildName -notlike '*_Classes' } | Select-Object -ExpandProperty PSChildName $items = [System.Collections.ArrayList]::new() foreach ($sid in $hkuSids) { try { $user = [System.Security.Principal.SecurityIdentifier]::new($sid).Translate([System.Security.Principal.NTAccount]).Value } catch { $user = "Unknown User ($sid)" } $items.Add([PSCustomObject]@{ Label = $user; SID = $sid; Checked = $false }) | Out-Null } if ($items.Count -eq 0) { # Fallback if no active profiles are found or access denied $items.Add([PSCustomObject]@{ Label = "$([Environment]::UserDomainName)\$([Environment]::UserName) (Current)"; SID = "HKCU"; Checked = $true }) | Out-Null } else { $items[0].Checked = $true # Select first by default } $res = Show-CheckListDialog "Select User Profile to analyze (Choose ONE, Space to toggle):" "Select User Profile" $items $width $height if ($null -eq $res) { return $null } foreach ($item in $res) { if ($item.Checked) { return $item # Return the first checked user profile object } } return $items[0] } # --- DATA RETRIEVAL --- function Get-DevicesAndPrinters($profile) { $sid = $profile.SID # 1. Fetch Printers from Registry $printers = [System.Collections.ArrayList]::new() $registryPath = if ($sid -eq "HKCU") { "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Devices" } else { "Registry::HKEY_USERS\$sid\Software\Microsoft\Windows NT\CurrentVersion\Devices" } $defaultPrinterName = "" $winRegPath = if ($sid -eq "HKCU") { "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows" } else { "Registry::HKEY_USERS\$sid\Software\Microsoft\Windows NT\CurrentVersion\Windows" } try { $defDevice = Get-ItemProperty $winRegPath -Name Device -ErrorAction SilentlyContinue if ($defDevice -and $defDevice.Device) { $defaultPrinterName = $defDevice.Device.Split(',')[0] } } catch {} # Get system-wide printer statuses (via native Get-Printer) $systemPrinters = @{} try { Get-Printer -ErrorAction SilentlyContinue | ForEach-Object { $systemPrinters[$_.Name] = $_.PrinterStatus.ToString() } } catch {} try { $regKeys = Get-ItemProperty $registryPath -ErrorAction SilentlyContinue if ($regKeys) { $props = $regKeys | Get-Member -MemberType NoteProperty $excludeProps = @('PSPath', 'PSParentPath', 'PSChildName', 'PSDrive', 'PSProvider', 'PSComputerName', 'RunspaceId') foreach ($prop in $props) { $pName = $prop.Name if ($excludeProps -contains $pName) { continue } $pValue = $regKeys.$pName $isDefault = ($pName -eq $defaultPrinterName) $status = if ($systemPrinters.ContainsKey($pName)) { $systemPrinters[$pName] } else { "Normal" } $printers.Add([PSCustomObject]@{ Name = $pName PortOrDriver = $pValue Status = $status IsDefault = if ($isDefault) { "YES" } else { "NO" } Type = "Printer" }) | Out-Null } } } catch {} # 2. Fetch User-Oriented Devices from PnpDevice $devices = Get-PnpDevice -ErrorAction SilentlyContinue | Where-Object { $_.Present } $monitors = [System.Collections.ArrayList]::new() $audio = [System.Collections.ArrayList]::new() $inputs = [System.Collections.ArrayList]::new() $bluetooth = [System.Collections.ArrayList]::new() foreach ($dev in $devices) { $class = $dev.Class $mappedDev = [PSCustomObject]@{ Name = if ($dev.FriendlyName) { $dev.FriendlyName } else { $dev.InstanceId } Class = $class Manufacturer = $dev.Manufacturer Status = $dev.Status Type = "Device" InstanceId = $dev.InstanceId } if ($class -eq "Monitor" -or $class -eq "Display") { $monitors.Add($mappedDev) | Out-Null } elseif ($class -eq "Media" -or $class -eq "AudioProcessingObject") { $audio.Add($mappedDev) | Out-Null } elseif ($class -eq "Keyboard" -or $class -eq "Mouse") { $inputs.Add($mappedDev) | Out-Null } elseif ($class -eq "Bluetooth") { $bluetooth.Add($mappedDev) | Out-Null } } # 3. Fetch Printer Ports $ports = [System.Collections.ArrayList]::new() try { Get-PrinterPort -ErrorAction SilentlyContinue | ForEach-Object { $ports.Add([PSCustomObject]@{ Name = $_.Name Description = $_.Description PortMonitor = $_.PortMonitor Type = "Port" }) | Out-Null } } catch {} # Pack everything return @{ Printers = $printers Monitors = $monitors Audio = $audio Inputs = $inputs Bluetooth = $bluetooth Ports = $ports } } # --- CATEGORIES TREE --- $categoriesTree = @( [PSCustomObject]@{ Id = "Printers"; Label = "Printers"; Level = 0; IsLeaf = $true } [PSCustomObject]@{ Id = "Ports"; Label = "Printer Ports"; Level = 0; IsLeaf = $true } [PSCustomObject]@{ Id = "Monitors"; Label = "Displays & Monitors"; Level = 0; IsLeaf = $true } [PSCustomObject]@{ Id = "Audio"; Label = "Audio & Multimedia"; Level = 0; IsLeaf = $true } [PSCustomObject]@{ Id = "Inputs"; Label = "Input Devices (KB/Mouse)"; Level = 0; IsLeaf = $true } [PSCustomObject]@{ Id = "Bluetooth"; Label = "Bluetooth Devices"; Level = 0; IsLeaf = $true } ) $printerCols = @( @{ Label = "Printer Name"; Prop = "Name"; Align = "Left"; Width = 25 } @{ Label = "Port / Driver Value"; Prop = "PortOrDriver"; Align = "Left"; Width = 30 } @{ Label = "Status"; Prop = "Status"; Align = "Left"; Width = 12 } @{ Label = "Default"; Prop = "IsDefault"; Align = "Center"; Width = 8 } ) $portCols = @( @{ Label = "Port Name"; Prop = "Name"; Align = "Left"; Width = 25 } @{ Label = "Description"; Prop = "Description"; Align = "Left"; Width = 25 } @{ Label = "Port Monitor"; Prop = "PortMonitor"; Align = "Left"; Width = 25 } ) $deviceCols = @( @{ Label = "Device Name"; Prop = "Name"; Align = "Left"; Width = 30 } @{ Label = "Class"; Prop = "Class"; Align = "Left"; Width = 12 } @{ Label = "Manufacturer"; Prop = "Manufacturer"; Align = "Left"; Width = 20 } @{ Label = "Status"; Prop = "Status"; Align = "Left"; Width = 10 } ) # --- STARTUP DIALOGS --- $width = [Console]::WindowWidth $height = [Console]::WindowHeight Initialize-Console [Console]::Write("$ESC[2J") # Prompt user selection $selectedProfile = Select-UserProfile $width $height if ($null -eq $selectedProfile) { Restore-Console Write-Host "No user profile selected. Exiting." exit } # Load profile data $data = Get-DevicesAndPrinters $selectedProfile $selectedCategoryIndex = 0 Update-LayoutDimensions $width $height $global:mainHeight = 12 # Override mainHeight to keep table at ~10 rows, maximizing details pane $tableSelectedIndex = 0 $tableScrollOffset = 0 $detailsScrollOffset = 0 $global:focusArea = 0 # 0: Categories, 1: Table, 2: Details $redrawAll = $true $needsTreeRedraw = $true $needsTableRedraw = $true $needsDetailsRedraw = $true $needsStatusRedraw = $true $statusText = "Analyzing profile: $($selectedProfile.Label). Use Arrows and Tab to navigate." try { while ($true) { $activeCategory = $categoriesTree[$selectedCategoryIndex] $activeItems = switch ($activeCategory.Id) { "Printers" { $data.Printers } "Ports" { $data.Ports } "Monitors" { $data.Monitors } "Audio" { $data.Audio } "Inputs" { $data.Inputs } "Bluetooth"{ $data.Bluetooth } } $activeCols = if ($activeCategory.Id -eq "Printers") { $printerCols } elseif ($activeCategory.Id -eq "Ports") { $portCols } else { $deviceCols } # 1. Resize Check $newWidth = [Console]::WindowWidth $newHeight = [Console]::WindowHeight if ($newWidth -ne $width -or $newHeight -ne $height) { $width = $newWidth $height = $newHeight Update-LayoutDimensions $width $height $global:mainHeight = 12 [Console]::Write("$ESC[2J") $redrawAll = $true } # 2. Redraw Components if ($redrawAll) { $rightWidth = $width - $global:leftWidth - 4 Draw-Borders $width $height $global:leftWidth $global:mainHeight $global:focusArea "CATEGORIES" "ITEMS IN CATEGORY" "PROPERTIES" $menuItems = if ($activeCategory.Id -eq "Printers") { @("Shift+D: Set Default", "Shift+A: Add Printer", "Shift+X: Delete Printer", "Shift+U: Change User", "Shift+R: Refresh", "Ctrl+Q: Exit") } elseif ($activeCategory.Id -eq "Ports") { @("Shift+A: Add Port", "Shift+X: Delete Port", "Shift+U: Change User", "Shift+R: Refresh", "Ctrl+Q: Exit") } else { @("Shift+U: Change User", "Ctrl+Q: Exit", "Shift+Q: Exit") } Draw-Menu $width $menuItems $needsTreeRedraw = $true $needsTableRedraw = $true $needsDetailsRedraw = $true $needsStatusRedraw = $true $redrawAll = $false } if ($needsTreeRedraw) { Draw-TreeView ([System.Collections.ArrayList]::new($categoriesTree)) $selectedCategoryIndex 0 $global:leftWidth ($height - 4) ($global:focusArea -eq 0) $needsTreeRedraw = $false } if ($needsTableRedraw) { $rightWidth = $width - $global:leftWidth - 4 if ($activeCategory.Id -eq "Printers") { # Printers: dynamically size Name (40%) and PortOrDriver (60%) $fixedW = 0 foreach ($col in $activeCols) { if ($col.Prop -ne 'Name' -and $col.Prop -ne 'PortOrDriver') { $fixedW += $col.Width + 1 } } $remainingW = $rightWidth - $fixedW - 2 if ($remainingW -lt 20) { $remainingW = 20 } $nameCol = $activeCols | Where-Object { $_.Prop -eq 'Name' } $portCol = $activeCols | Where-Object { $_.Prop -eq 'PortOrDriver' } if ($nameCol -and $portCol) { $nameCol.Width = [int]($remainingW * 0.40) if ($nameCol.Width -lt 10) { $nameCol.Width = 10 } $portCol.Width = $remainingW - $nameCol.Width if ($portCol.Width -lt 10) { $portCol.Width = 10 } } } else { # Devices: dynamically size Name to fill remainder $totalW = 0 foreach ($col in $activeCols) { if ($col.Prop -ne 'Name') { $totalW += $col.Width + 1 } } $nameCol = $activeCols | Where-Object { $_.Prop -eq 'Name' } if ($nameCol) { $nameCol.Width = $rightWidth - $totalW - 1 if ($nameCol.Width -lt 10) { $nameCol.Width = 10 } } } Draw-TableHeader ($global:leftWidth + 2) 2 $activeCols $rightWidth Draw-TableRows $activeItems $tableSelectedIndex $tableScrollOffset $activeCols ($global:leftWidth + 2) 3 $rightWidth ($global:mainHeight - 2) ($global:focusArea -eq 1) $needsTableRedraw = $false } if ($needsDetailsRedraw) { $rightWidth = $width - $global:leftWidth - 4 $selectedItem = if ($activeItems.Count -gt 0 -and $tableSelectedIndex -lt $activeItems.Count) { $activeItems[$tableSelectedIndex] } else { $null } $itemDetails = [System.Collections.ArrayList]::new() if ($null -ne $selectedItem) { if ($selectedItem.Type -eq "Printer") { $itemDetails.Add("PRINTER PROPERTIES") | Out-Null $itemDetails.Add("-" * 18) | Out-Null $itemDetails.Add("Printer Name: $($selectedItem.Name)") | Out-Null $itemDetails.Add("Port/Driver: $($selectedItem.PortOrDriver)") | Out-Null $itemDetails.Add("Status: $($selectedItem.Status)") | Out-Null $itemDetails.Add("Is Default: $($selectedItem.IsDefault)") | Out-Null $itemDetails.Add("Profile SID: $($selectedProfile.SID)") | Out-Null } elseif ($selectedItem.Type -eq "Port") { $itemDetails.Add("PRINTER PORT PROPERTIES") | Out-Null $itemDetails.Add("-" * 23) | Out-Null $itemDetails.Add("Port Name: $($selectedItem.Name)") | Out-Null $itemDetails.Add("Description: $($selectedItem.Description)") | Out-Null $itemDetails.Add("Port Monitor: $($selectedItem.PortMonitor)") | Out-Null } else { $itemDetails.Add("DEVICE PROPERTIES") | Out-Null $itemDetails.Add("-" * 18) | Out-Null $itemDetails.Add("Device Name: $($selectedItem.Name)") | Out-Null $itemDetails.Add("Class: $($selectedItem.Class)") | Out-Null $itemDetails.Add("Manufacturer: $($selectedItem.Manufacturer)") | Out-Null $itemDetails.Add("Status: $($selectedItem.Status)") | Out-Null $itemDetails.Add("Instance ID: $($selectedItem.InstanceId)") | Out-Null } } else { $itemDetails.Add("No item selected.") | Out-Null } $detailHeight = $height - $global:mainHeight - 4 Draw-Details $null $itemDetails $detailsScrollOffset ($global:leftWidth + 2) ($global:mainHeight + 2) $rightWidth $detailHeight $needsDetailsRedraw = $false } if ($needsStatusRedraw) { $focusTxt = switch ($global:focusArea) { 0 { "Categories" } 1 { "Table" } 2 { "Details" } } Draw-Status $statusText $focusTxt "Tab: Switch Pane" $width $height $needsStatusRedraw = $false } Set-Cursor 0 0 # 3. Read Key Input if (-not [Console]::KeyAvailable) { Start-Sleep -Milliseconds 20 continue } $key = [Console]::ReadKey($true) $isCtrl = ($key.Modifiers -band [System.ConsoleModifiers]::Control) -eq [System.ConsoleModifiers]::Control $isShift = ($key.Modifiers -band [System.ConsoleModifiers]::Shift) -eq [System.ConsoleModifiers]::Shift if (($isCtrl -or $isShift) -and $key.Key -eq 'Q') { break } # Printer manipulation commands if ($isShift -and $key.Key -eq 'D' -and $activeCategory.Id -eq "Printers") { # Set default printer $selectedPrinter = if ($data.Printers.Count -gt 0) { $data.Printers[$tableSelectedIndex] } else { $null } if ($selectedPrinter) { $statusText = "Setting default printer to $($selectedPrinter.Name)..." $needsStatusRedraw = $true Draw-Status $statusText "" "" $width $height $sid = $selectedProfile.SID $winRegPath = if ($sid -eq "HKCU") { "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows" } else { "Registry::HKEY_USERS\$sid\Software\Microsoft\Windows NT\CurrentVersion\Windows" } try { # Format standard device string: PrinterName,winspool,Port $port = $selectedPrinter.PortOrDriver.Split(',')[1] if (-not $port) { $port = "Ne00:" } $deviceValue = "$($selectedPrinter.Name),winspool,$port" Set-ItemProperty -Path $winRegPath -Name Device -Value $deviceValue -ErrorAction Stop $statusText = "Default printer changed successfully." } catch { $statusText = "Failed to change default printer: " + $_.Exception.Message } # Reload $data = Get-DevicesAndPrinters $selectedProfile } $redrawAll = $true continue } if ($isShift -and $key.Key -eq 'A' -and $activeCategory.Id -eq "Printers") { # Add Printer connection $pName = Show-InputBox "Enter Printer Name to add:" "Add Printer" $width $height if (-not [string]::IsNullOrEmpty($pName)) { $pPort = Show-InputBox "Enter Port / Driver value (e.g. winspool,Ne00:):" "Add Printer" $width $height if ([string]::IsNullOrEmpty($pPort)) { $pPort = "winspool,Ne00:" } $statusText = "Adding printer registry key..." $needsStatusRedraw = $true Draw-Status $statusText "" "" $width $height $sid = $selectedProfile.SID $registryPath = if ($sid -eq "HKCU") { "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Devices" } else { "Registry::HKEY_USERS\$sid\Software\Microsoft\Windows NT\CurrentVersion\Devices" } try { Set-ItemProperty -Path $registryPath -Name $pName -Value $pPort -ErrorAction Stop $statusText = "Printer connection added successfully." } catch { $statusText = "Failed to add printer: " + $_.Exception.Message } # Reload $data = Get-DevicesAndPrinters $selectedProfile } $redrawAll = $true continue } if ($isShift -and $key.Key -eq 'X' -and $activeCategory.Id -eq "Printers") { # Delete Printer connection $selectedPrinter = if ($data.Printers.Count -gt 0) { $data.Printers[$tableSelectedIndex] } else { $null } if ($selectedPrinter) { $confirm = Show-InputBox "Type 'confirm' to confirm deleting printer $($selectedPrinter.Name):" "Confirm Delete Printer" $width $height if ($confirm -eq 'confirm') { $statusText = "Deleting printer registry key..." $needsStatusRedraw = $true Draw-Status $statusText "" "" $width $height $sid = $selectedProfile.SID $registryPath = if ($sid -eq "HKCU") { "Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Devices" } else { "Registry::HKEY_USERS\$sid\Software\Microsoft\Windows NT\CurrentVersion\Devices" } try { Remove-ItemProperty -Path $registryPath -Name $selectedPrinter.Name -ErrorAction Stop $statusText = "Printer connection removed." } catch { $statusText = "Failed to delete printer: " + $_.Exception.Message } # Reload $data = Get-DevicesAndPrinters $selectedProfile $tableSelectedIndex = 0 $tableScrollOffset = 0 } else { $statusText = "Delete cancelled." } } $redrawAll = $true continue } if ($isShift -and $key.Key -eq 'A' -and $activeCategory.Id -eq "Ports") { # Add Printer Port $portName = Show-InputBox "Enter Port Name (e.g. IP_192.168.1.100 or LPT2:):" "Add Printer Port" $width $height if (-not [string]::IsNullOrEmpty($portName)) { $portTypes = [System.Collections.ArrayList]::new(@("Standard TCP/IP Port", "Local Port")) $typeIdx = Show-ListSelectionDialog "Select Port Type:" "Port Type" $portTypes 0 $width $height if ($null -ne $typeIdx) { $statusText = "Adding printer port..." $needsStatusRedraw = $true Draw-Status $statusText "" "" $width $height try { if ($typeIdx -eq 0) { # TCP/IP Port $hostAddress = $portName -replace '^IP_', '' $ipPrompt = Show-InputBox "Enter Printer Host Address (default: $hostAddress):" "TCP/IP Address" $width $height if (-not [string]::IsNullOrEmpty($ipPrompt)) { $hostAddress = $ipPrompt } Add-PrinterPort -Name $portName -PrinterHostAddress $hostAddress -ErrorAction Stop } else { # Local Port Add-PrinterPort -Name $portName -ErrorAction Stop } $statusText = "Printer port '$portName' added successfully." } catch { $statusText = "Failed to add port: " + $_.Exception.Message } # Reload $data = Get-DevicesAndPrinters $selectedProfile } } $redrawAll = $true continue } if ($isShift -and $key.Key -eq 'X' -and $activeCategory.Id -eq "Ports") { # Delete Printer Port $selectedPort = if ($data.Ports.Count -gt 0) { $data.Ports[$tableSelectedIndex] } else { $null } if ($selectedPort) { $confirm = Show-InputBox "Type 'confirm' to confirm deleting port $($selectedPort.Name):" "Confirm Delete Port" $width $height if ($confirm -eq 'confirm') { $statusText = "Deleting printer port $($selectedPort.Name)..." $needsStatusRedraw = $true Draw-Status $statusText "" "" $width $height try { Remove-PrinterPort -Name $selectedPort.Name -ErrorAction Stop $statusText = "Printer port removed successfully." } catch { $statusText = "Failed to delete port: " + $_.Exception.Message } # Reload $data = Get-DevicesAndPrinters $selectedProfile $tableSelectedIndex = 0 $tableScrollOffset = 0 } else { $statusText = "Delete cancelled." } } $redrawAll = $true continue } if ($isShift -and $key.Key -eq 'U') { # Change user profile $newProfile = Select-UserProfile $width $height if ($null -ne $newProfile) { $selectedProfile = $newProfile $statusText = "Loading new profile: $($selectedProfile.Label)..." $needsStatusRedraw = $true Draw-Status $statusText "" "" $width $height $data = Get-DevicesAndPrinters $selectedProfile $selectedCategoryIndex = 0 $tableSelectedIndex = 0 $tableScrollOffset = 0 $detailsScrollOffset = 0 $statusText = "Loaded profile: $($selectedProfile.Label)." } $redrawAll = $true continue } if ($isShift -and $key.Key -eq 'R') { # Refresh $statusText = "Refreshing data..." $needsStatusRedraw = $true Draw-Status $statusText "" "" $width $height $data = Get-DevicesAndPrinters $selectedProfile $statusText = "Data refreshed." $redrawAll = $true continue } # --- FOCUS NAVIGATION --- if ($global:focusArea -eq 0) { # Categories Tree if ($key.Key -eq 'UpArrow') { if ($selectedCategoryIndex -gt 0) { $selectedCategoryIndex-- $tableSelectedIndex = 0 $tableScrollOffset = 0 $detailsScrollOffset = 0 $needsTreeRedraw = $true $needsTableRedraw = $true $needsDetailsRedraw = $true } } elseif ($key.Key -eq 'DownArrow') { if ($selectedCategoryIndex -lt ($categoriesTree.Count - 1)) { $selectedCategoryIndex++ $tableSelectedIndex = 0 $tableScrollOffset = 0 $detailsScrollOffset = 0 $needsTreeRedraw = $true $needsTableRedraw = $true $needsDetailsRedraw = $true } } elseif ($key.Key -eq 'Tab') { if ($activeItems.Count -gt 0) { $global:focusArea = 1 } else { $global:focusArea = 2 } $redrawAll = $true } } elseif ($global:focusArea -eq 1) { # Items Table $tableHeight = $global:mainHeight - 2 if ($key.Key -eq 'UpArrow') { if ($tableSelectedIndex -gt 0) { $tableSelectedIndex-- if ($tableSelectedIndex -lt $tableScrollOffset) { $tableScrollOffset = $tableSelectedIndex } $detailsScrollOffset = 0 $needsTableRedraw = $true $needsDetailsRedraw = $true } } elseif ($key.Key -eq 'DownArrow') { if ($tableSelectedIndex -lt ($activeItems.Count - 1)) { $tableSelectedIndex++ if ($tableSelectedIndex -ge ($tableScrollOffset + $tableHeight)) { $tableScrollOffset = $tableSelectedIndex - $tableHeight + 1 } $detailsScrollOffset = 0 $needsTableRedraw = $true $needsDetailsRedraw = $true } } elseif ($key.Key -eq 'PageUp') { $tableSelectedIndex = [Math]::Max(0, $tableSelectedIndex - $tableHeight) $tableScrollOffset = [Math]::Max(0, $tableScrollOffset - $tableHeight) if ($tableSelectedIndex -lt $tableScrollOffset) { $tableSelectedIndex = $tableScrollOffset } $detailsScrollOffset = 0 $needsTableRedraw = $true $needsDetailsRedraw = $true } elseif ($key.Key -eq 'PageDown') { $tableSelectedIndex = [Math]::Min($activeItems.Count - 1, $tableSelectedIndex + $tableHeight) $tableScrollOffset = [Math]::Min($activeItems.Count - $tableHeight, $tableScrollOffset + $tableHeight) if ($tableScrollOffset -lt 0) { $tableScrollOffset = 0 } if ($tableSelectedIndex -ge ($tableScrollOffset + $tableHeight)) { $tableSelectedIndex = $tableScrollOffset + $tableHeight - 1 } $detailsScrollOffset = 0 $needsTableRedraw = $true $needsDetailsRedraw = $true } elseif ($key.Key -eq 'Escape') { $global:focusArea = 0 $redrawAll = $true } elseif ($key.Key -eq 'Tab') { $isShift = ($key.Modifiers -band [System.ConsoleModifiers]::Shift) -eq [System.ConsoleModifiers]::Shift $global:focusArea = if ($isShift) { 0 } else { 2 } $redrawAll = $true } } elseif ($global:focusArea -eq 2) { # Details View scrolling $detailHeight = $height - $global:mainHeight - 4 # Estimate detail lines count $detailsCount = if ($activeCategory.Id -eq "Printers") { 8 } else { 8 } if ($key.Key -eq 'UpArrow') { if ($detailsScrollOffset -gt 0) { $detailsScrollOffset-- $needsDetailsRedraw = $true } } elseif ($key.Key -eq 'DownArrow') { if ($detailsScrollOffset -lt ($detailsCount - $detailHeight)) { $detailsScrollOffset++ $needsDetailsRedraw = $true } } elseif ($key.Key -eq 'Tab') { $isShift = ($key.Modifiers -band [System.ConsoleModifiers]::Shift) -eq [System.ConsoleModifiers]::Shift $global:focusArea = if ($isShift) { if ($activeItems.Count -gt 0) { 1 } else { 0 } } else { 0 } $redrawAll = $true } elseif ($key.Key -eq 'Escape') { $global:focusArea = 0 $redrawAll = $true } } } } finally { Restore-Console } |