无法从 Powershell Windows 窗体文本框获取字符串

问题描述 投票:0回答:2

因此,我一直在工作场所为我的一个脚本开发 GUI,但我无法从用户可以将文本放入的文本框中获取任何文本字符串。我已经创建了一个我想做的事情的准系统版本来尝试解决这个问题。单击时,我将“确定”按钮设置为

Write-Host $input.text
。当我单击“确定”时,控制台只输出任何内容,一个空格。

我尝试重新排列我的代码,添加

-Out-String
,并添加
.ToString()
,最终表明输入为空。即使我在运行脚本时将文本设置为“Test”之类的内容,输出仍然为空。

这是我的代码:

[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 窗体的这种方法,因为我的完整窗体会很复杂。

powershell winforms
2个回答
0
投票

您的代码的问题在于,回调(

$run
$exit
)是在您添加它们之后定义的,而不是在before之前定义的,因此您实际上是将null
添加到那些
.Click
事件中。改变一下顺序,先定义一下就好了。

此外,不建议使用

$input

 作为变量名。 
$input
 是 PowerShell 中的自动变量

[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' } $textBox = 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 $run = { Write-Host $textBox.Text } #Output input box text $exit = { $form.Close() } $confirm.Add_Click($run) $close.Add_Click($exit) $form.Controls.Add($confirm) $form.Controls.Add($close) $form.Controls.Add($textBox) $form.Add_Shown({ $this.Activate() }) $form.ShowDialog()
    

0
投票

使用 Microsoft 的示例作为起点

© www.soinside.com 2019 - 2024. All rights reserved.