Search code examples
powershelluser-interfacepowershell-3.0powershell-4.0

Update GUI in Powershell


I want to write a programm which has a Kind of traffic light funtion. The color of the Frame should be changed depending on an check. I already solved the check of the criterias, so in this example the while-Loop is vicarious for a bigger check. But to focus on the problem i shortend it like this. My problem is that i can´t update the Color of the UI.

So the program should be running all the time, but it seems to be stuck at:

[void] $Form.ShowDialog()

and only will continue after I close the form. So how can i bypass this section to get into the infinit Loop, so that my Form is shown all the time with changing Color?

    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Test"
$Form.Size = New-Object System.Drawing.Size(300,300)
$Form.StartPosition = "CenterScreen"
$Form.BackColor = "Green"

$Form.Topmost = $True
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()

while ($True)
    $test = Get-Content -Path C:\Users\admin\Documents\pro.txt
    if ($test -eq 2)
    {
    $Form.BackColor = "Green"
    } else {
    $Form.BackColor = "Red"
    }
     Start-Sleep -s 2

}

Thanks for you help!


Solution

  • $Form.ShowDialog()
    

    This line requires interaction on the form. The code following that line will not run until the form is closed. Another way to launch the form would be like the following

    $Form.Show()
    

    If you launch the form like that, the code should continue to run. Although you still may need a better solution, as your following code uses start-sleep -s 2. I believe this might also make your form sleep, which would render it potentially unusable.

    I would recommend learning about PowerShell Event Handlers here. There might be a better solution using an event handler for your solution. An example of an event handler follows

    $Form_Load {
         # Your commands and stuff here #
    }
    

    The $Form is the object that the event is looking at, then you have a separator _, then Load is the name of the actual event that when executed the code runs. So any of the code inside those brackets will run right away when form $Form is launched. This can be anything from loading a form, clicking a button, or even a selected index changing inside of a listbox.

    Event handlers took my PowerShell GUI building abilities to then next level when it comes to what I had the ability to do with the form. So I would highly recommend learning about event handlers if PowerShell GUIs are the normal for you, the most helpful tool you could buy is SAPIEN PowerShell Studio which is an extremely helpful development environment. It is basically a Visual Studio built just for PowerShell. I think it's in the $400-$500 range.