【问题标题】:MessageBox only showing after form is closedMessageBox 仅在表单关闭后显示
【发布时间】: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


【解决方案1】:

您必须在调用ShowDialog(基本上是您设置该按钮的位置)之前添加您的点击处理程序,并且必须以这种方式添加:

$searchButton.Add_Click(
  {
    $status = (Get-MyCustomFunction $unameTextBox.Text)
    [System.Windows.Forms.Messagebox]::Show($status)
  }
)

更多信息例如在这里:https://social.technet.microsoft.com/wiki/contents/articles/25911.how-to-add-a-powershell-gui-event-handler-part-1.aspx

【讨论】:

  • 非常感谢,成功了。我最初尝试过,但最后没有ShowDialog()。填充textBox后允许'Enter'触发按钮是否容易?
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
相关资源
最近更新 更多