Centering a window after loading

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Locked
User avatar
rmckay9969
Posts: 63
Joined: Fri Oct 30, 2015 4:24 pm

Centering a window after loading

Post by rmckay9969 » Mon Sep 26, 2016 10:02 pm

I realize that this is generally a Q & A based forum, however I thought it would be helpful to give a solution I came across. I have a program that loads all the filenames in a directory needing a place holder value replaced with real world data. For example a filename containing a milepost of 100.XX would need the fractional portion added once verified. This program loads the full path of the file into a datagrid and once the place holder of XX is replaced with actual data, it renames the file in the directory. Simple enough, but I have a major gripe about re-sizing a form manually to show the full length of text it contains. And a form that is not centered after programmatically resizing just does not look very nice. This solution although possibly crude provides both resizing to fit contents and centering to the main form. Hopefully useful to somebody as I was not able to find a good example and had to do some research to make a powershell/winforms result.

Code: Select all

$foldername = New-Object System.Windows.Forms.FolderBrowserDialog
$font = New-Object System.Drawing.Font("Verdana", 9, [System.Drawing.FontStyle]::Bold)
$Width = 0
$Height = 0
if ($foldername.ShowDialog() -eq "OK") {
$Count = (Get-ChildItem $foldername.SelectedPath -Filter *.txt | Measure-Object).Count
$list = foreach ($_ in Get-ChildItem $foldername.SelectedPath -Filter *.txt) {
$Text = $_.FullName
# Get the length in pixels of the text string based off of font & Size
$SizeW = [System.Windows.Forms.TextRenderer]::MeasureText([string]$Text, $font).Width
# Get the Height in pixels of the text string based off of font & Size
$SizeH = [System.Windows.Forms.TextRenderer]::MeasureText([string]$Text, $font).Height
$Width = $Width + $SizeW
$Height = $Height + $SizeH + 2 # A little more padding if needed
New-Object PsObject -Property @{ HeaderName = $_.FullName }
}
# Average the text lengths and add some padding
$form1.Width = $Width / $Count + 200
# A little more padding if needed
$form1.Height = $Height + 150
}
# Center the form to the main form
$form1.Left = $mainform.Left + (0.5 * $mainform.Width) - (0.5 * $form1.Width)
$form1.Top = $mainform.Top + (0.5 * $mainform.Height) - (0.5 * $form1.Height)

Locked