【发布时间】:2019-11-02 14:38:15
【问题描述】:
创建一个简单的 GUI 以使用给定的用户名作为参数运行自定义函数。
点击搜索按钮后,我需要将自定义函数的结果返回给用户。最好不要关闭整个东西并允许他们再次搜索,但这是我第一次构建 GUI
import-module "{path to my custom module}"
#region Prereqs
[reflection.assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
#endregion
#region Create Window with textbox and button
$searchForm = New-Object System.Windows.Forms.Form
$unameTextBox = New-Object System.Windows.Forms.TextBox
$searchButton = New-Object System.Windows.Forms.Button
$unameTextBox.Location = '23,23'
$unameTextBox.Size = '150,23'
$unameTextBox.Text = 'Enter username...'
$searchButton.Text = 'Search'
$searchButton.Location = '196,23'
$searchForm.Controls.Add($unameTextBox)
$searchForm.Controls.Add($searchButton)
$searchForm.Text = 'Lit hold search'
$searchForm.ShowDialog()
#function takes 1 argument (uname), performs AD lookup and returns True/False
$status = (Get-MyCustomFunction $unameTextBox.Text)
$searchButton.Add_Click([System.Windows.Forms.Messagebox]::Show($status))
#endregion
我希望单击搜索按钮后会弹出消息框。相反,它仅在表单关闭后显示。理想情况下,我希望保持表单打开并允许进行其他搜索。也许有比消息框更好的选择来显示简单的消息?
编辑:
如果提供额外的上下文,我现在会收到以下错误...
Cannot convert argument "value", with value: "OK", for "add_Click" to type "System.EventHandler": "Cannot convert value "OK" to type "System.EventHandler". Error: "Invalid cast from
'System.Windows.Forms.DialogResult' to 'System.EventHandler'.""
At C:\Modules\lithold.ps1:33 char:1
+ $searchButton.Add_Click([System.Windows.Forms.Messagebox]::Show($stat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
【问题讨论】:
-
将
$searchForm.ShowDialog()行移至最后一行。在其下方添加$searchForm.Dispose()。 -
如果我将该行移到
$searchButton.Add_Click([System.Windows.Forms.Messagebox]::Show($status))下方,它会在单击“搜索”按钮之前显示消息框。它还使用占位符文本执行函数,因为它还没有收到用户输入。
标签: .net winforms powershell user-interface