I'm writing a script for a user that concatenates several PDF files and appends tabular data as a text file. Now the problem is that the user can manually name the text files so that the script has to verify which PDF file belongs to the data. Usually it would do so by name, but since the user can (and will obviously) change the name of the PDF, the script shall ask the user to pick the correct PDF to merge.
I've written a function in my script, that uses Winforms to display a Listbox with the available PDF files and the user should pick one.
function Select-Rechnung
{
param
(
[string] $Rechnung,
[string[]] $PdfFiles
)
$form = New-Object System.Windows.Forms.Form
$form.Text = "Rechnung wählen"
$form.Size = New-Object System.Drawing.Size(640,320)
$form.StartPosition = "CenterScreen"
$form.KeyPreview = $true
$form.Add_KeyDown({if($_.KeyCode -eq "Enter") { $x = $PdfFiles[$ListBox.SelectedIndex]; $form.Close() }})
$form.Add_KeyDown({if($_.KeyCode -eq "Escape") { $form.Close() }})
$OkButton = New-Object System.Windows.Forms.Button
$OkButton.Location = New-Object System.Drawing.Size(240,240)
$OkButton.Size = New-Object System.Drawing.Size(75,23)
$OkButton.Text = "OK"
$OkButton.Add_Click({ $x = $PdfFiles[$ListBox.SelectedIndex]; $form.Close() })
$form.Controls.Add($OkButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(325,240)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Abbrechen"
$CancelButton.Add_Click({$form.Close()})
$form.Controls.Add($CancelButton)
$Label = New-Object System.Windows.Forms.Label
$Label.Location = New-Object System.Drawing.Size(10,20)
$Label.Size = New-Object System.Drawing.Size(600,20)
$Label.Text = [string]::Format("Für die Rechnung {0} wurden mehrere mögliche Dateien gefunden. Bitte auswählen:", $Rechnung)
$form.Controls.Add($Label)
$ListBox = New-Object System.Windows.Forms.ListBox
$ListBox.Location = New-Object System.Drawing.Size(10,40)
$ListBox.Size = New-Object System.Drawing.Size(600, 20)
$ListBox.Height = 200
foreach($pdfFile in $PdfFiles)
{
[void] $ListBox.Items.Add($pdfFile)
}
$form.Controls.Add($ListBox)
$form.TopMost = $true
$form.Add_Shown({$form.Activate()})
[void] $form.ShowDialog()
$x
}
Now within the KeyDown
handler or the Click
handler, the function should assign the selected PDF file to the variable $x
. I've checked that the $PdfFiles
are correctly handed to the function and that during the handlers execution, the $PdfFiles[$ListBox.SelectedIndex]
actually has the correct string value. However, when I access $x
after the forms ShowDialog
has been processed, it is empty and thus the function's return value is empty.
Why won't it assign the value (that it correctly evaluates during the handler) to my variable and return it?