创建一个简单的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
答案 0 :(得分:1)
您必须在调用ShowDialog
(基本上是在该按钮的设置位置)之前添加要单击的处理程序,并且必须通过以下方式添加它:
$searchButton.Add_Click(
{
$status = (Get-MyCustomFunction $unameTextBox.Text)
[System.Windows.Forms.Messagebox]::Show($status)
}
)