I have a script which, at its start, creates several dialog boxes to ask for input data. First a message appears “Select target folder”. After clicking, a folder browser appears to allow the user to select the folder. Then another message box with “select source file” appears, after clicking it a file browser appears to select a source file. Lastly, message box with “select a template” appears and after clicking file browser appears to allow user to select a template which will be used during the script execution.
Problem is, that the dialogs behave erratically. Most of the time the message boxes appear in the background, which is rather confusing since the user likely does not notice it. Another problem is, that when the script is run on a computer with two connected displays, message boxes appear on one display, browsers on the other. And the most confusing thing is that all of that is MOSTLY, not always. Sometimes the message boxes appear on the top (most frequently the first one). Here’s the relevant code:
function Show-MessageBox {
param (
[string]$message
)
[System.Windows.Forms.MessageBox]::Show($message, "Information", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information)
}
function Select-FolderDialog {
$folderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
$folderBrowser.Description = "Select the target folder"
$folderBrowser.ShowNewFolderButton = $true
if ($folderBrowser.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
return $folderBrowser.SelectedPath
} else {
Write-Host "Folder selection canceled."
exit
}
}
function Select-FileDialog {
$fileBrowser = New-Object System.Windows.Forms.OpenFileDialog
$fileBrowser.Filter = "Excel Files|*.xlsx"
$fileBrowser.Title = "Select a file"
if ($fileBrowser.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
return $fileBrowser.FileName
} else {
Write-Host "File selection canceled."
exit
}
}
# Display messages and prompt for input using dialogs
Show-MessageBox -message "Vyber cílovou složku."
$targetFolder = Select-FolderDialog
Show-MessageBox -message "Vyber zdrojový soubor"
$dataFilePath = Select-FileDialog
Show-MessageBox -message "Vyber šablonu"
$templateFilePath = Select-FileDialog
How do I keep all the six windows on one screen (preferably the one on which the script was run) and on top so that I don’t have to switch to them every time?