因此,我一直在工作场所为我的一个脚本开发 GUI,但我无法从用户可以将文本放入的文本框中获取任何文本字符串。我已经创建了一个我想做的事情的准系统版本来尝试解决这个问题。我将“确定”按钮设置为Write-Host $input.text
单击时。当我单击“确定”时,控制台仅输出任何内容,仅输出一个空格。
我尝试重新排列我的代码,添加-Out-String
,然后添加.ToString()
最终表示输入为空。即使我在运行脚本时将文本设置为“测试”之类的内容,输出仍然为空。
这是我的代码:
[void][System.Reflection.Assembly]::Load('System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][System.Reflection.Assembly]::Load('System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object System.Windows.Forms.Form -Property @{
Name = 'Test'
Text = 'Test'
}
$input = New-Object System.Windows.Forms.TextBox -Propert @{
Name = "Input"
Size = "200,200"
} #Input Textbox
$confirm = New-Object System.Windows.Forms.Button -Property @{
Text = "Ok"
Name = "confirm"
Location = "0,210"
} #confirm button
$close = New-Object System.Windows.Forms.Button -Property @{
Text = "Close"
Name = "Close"
Location = "100,210"
} #close button
$confirm.Add_Click($run)
$close.Add_Click($exit)
$form.Controls.Add($confirm)
$form.Controls.Add($close)
$form.Controls.Add($input)
$run = {Write-Host $input.Text} #Output input box text
$exit = {
$form.Close()
}
$form.ShowDialog()
$form.BringToFront()
如果我可以从输入框中获取文本,那么我就可以开始了,因为我只需要用户提供的字符串来完成我需要做的事情。我还想坚持使用 Windows 窗体的这种方法,因为完整形式的窗体会很复杂。
您的代码的问题在于,回调 (
$run
和$exit
) 是在您添加它们之后而不是之前定义的,因此您实际上是在添加null
这些.Click
事件。改变一下顺序,先定义一下就可以了。$input
另外,不建议使用as 变量名。是PowerShell 中的$input
自动变量。您可以大大缩短此时间。请注意,调用会
ShowDialog
发送一个返回值,需要测试该返回值以查看按下了哪个按钮,如以下工作示例所示:使用 Microsoft 的示例作为起点