自制PowerShell InputBox仅返回Cancel,密码框无法获取输入值
PowerShell WinForms密码输入框返回"Cancel"的问题修复
你的代码存在两个关键问题导致无法正确获取密码输入值:
- 变量名错误:设置
AcceptButton时用了未定义的$form,应该是$inpForm,这会导致回车无法触发OK按钮,且影响对话框结果判断。 - 返回值逻辑错误:按钮点击事件中的
return无法将值传递给函数,ShowDialog()默认返回对话框的操作结果(比如关闭窗口时默认是Cancel),需要手动设置对话框结果并在函数末尾返回输入框内容。
修复后的完整代码:
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [System.Windows.Forms.Application]::EnableVisualStyles() function InputForm { param($loggedInUser="Spock") $inpForm = New-Object System.Windows.Forms.Form $inpForm.Height = 120 $inpForm.Width = 350 $inpForm.Text = "Authentication Window" $inpForm.MaximizeBox = $false $inpForm.MinimizeBox = $false $inpForm.FormBorderStyle = "FixedDialog" $inpForm.StartPosition = "CenterScreen" $inpForm.Topmost = $true # 标签控件 $inpLbl = New-Object System.Windows.Forms.Label $inpLbl.Width = 300 $inpLbl.Location = New-Object System.Drawing.Point(10,10) $inpLbl.Text = "Please type in the password for user: " + $loggedInUser # 密码输入框 $inpBox = New-Object System.Windows.Forms.TextBox $inpBox.Width = 200 $inpBox.Height = 25 $inpBox.PasswordChar = "*" $inpBox.Location = New-Object System.Drawing.Point(10, 35) # OK按钮 $inpBtn = New-Object System.Windows.Forms.Button $inpBtn.Width = 60 $inpBtn.Height = 25 $inpBtn.Text = "OK" $inpBtn.Location = New-Object System.Drawing.Point(250,33) # 修正变量名,绑定AcceptButton到正确的表单对象 $inpForm.AcceptButton = $inpBtn $inpForm.Controls.AddRange(@($inpLbl, $inpBox, $inpBtn)) # OK按钮点击事件:设置对话框结果为OK,然后关闭窗口 $inpBtn.Add_Click({ $inpForm.DialogResult = [System.Windows.Forms.DialogResult]::OK $inpForm.Close() }) # 显示对话框并获取结果 $dialogResult = $inpForm.ShowDialog() # 根据对话框结果返回对应值 if ($dialogResult -eq [System.Windows.Forms.DialogResult]::OK) { return $inpBox.Text } else { return $null } } # 主程序 $currentUser = (Get-WMIObject -ClassName Win32_ComputerSystem).Username $PW = InputForm -loggedInUser $currentUser Write-Host "输入的密码:$PW"
关键修复点说明:
- 修正
$inpForm.AcceptButton = $inpBtn,确保回车能触发OK按钮,同时让对话框正确返回OK结果。 - 在按钮点击事件中设置
$inpForm.DialogResult = [System.Windows.Forms.DialogResult]::OK,这样ShowDialog()会返回OK,函数可以据此判断用户是否点击了OK按钮。 - 在
ShowDialog()之后,根据对话框结果决定返回输入框的文本还是空值,确保只有用户确认后才返回输入的密码。
内容的提问来源于stack exchange,提问作者Bernd
相关产品推荐
相关产品推荐

