Shivabelieva
Shivabelieva

Reputation: 33

MessageBox only showing after form is closed

Creating a simple GUI to run a custom function with a given username as an argument.

After the search button is clicked, I need to return the result of my custom function to the user. Preferably without closing the whole thing and allowing them to search again but it's my first time building a 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

I expect the message box to pop up after the search button is clicked. Instead it shows up only after the form has been closed. Ideally I would like to keep the form open and allow for additional searches. Maybe there is a better option than messagebox to display a simple message?

Edit:

I'm getting the following error now if that provides additional context...

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

Upvotes: 1

Views: 312

Answers (1)

Stano Peťko
Stano Peťko

Reputation: 166

You have to add your handler for click before calling ShowDialog (basically where you setup that button) and it has to be added this way:

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

More info for example here: https://social.technet.microsoft.com/wiki/contents/articles/25911.how-to-add-a-powershell-gui-event-handler-part-1.aspx

Upvotes: 1

Related Questions