Search code examples
wpfpowershellxamlrefreshwebbrowser-control

PowerShell Form with Web Browser that Automatically Refreshes


I'm trying to create a simple form in PowerShell in a small window that always stays on top other windows and just contains a web browser object that automatically refreshes every 10 seconds. I've been searching online and trying various options but nothing seems to work. Almost every example I come across has the form or web browser refresh happen on a button press, but I need the web browser to automatically refresh on its own without any user interaction. From what I've been reading it sounds like WPF (Windows Presentation Foundation) with XAML (Extensible Application Markup Language) is the way to go, since WinForms is limited into a single thread, which makes refreshing the form more difficult or perhaps impossible to accomplish effectively.

For now this is what I have (testing with google) without the automatic refresh:

[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = @'
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="PowerShell HTML GUI" WindowStartupLocation="Manual">
    <Grid>
        <WebBrowser
            HorizontalAlignment="Left"
            Width="415"
            Height="340"
            Margin="10,10,0,0"
            VerticalAlignment="Top"
            Name="WebBrowser"
        />
    </Grid>
</Window>
'@
$reader = New-Object System.Xml.XmlNodeReader($xaml)
$Form = [Windows.Markup.XamlReader]::Load($reader)
$Form.Width = 415
$Form.Height = 340
$Form.Topmost = $True
$WebBrowser = $Form.FindName('WebBrowser')
$WebBrowser.add_Loaded({$this.Navigate('http://www.google.com')})
$Form.ShowDialog()

I tried adding the following loop at the end of the code to replace $Form.ShowDialog(), but obviously this isn't going to work.

While (1) {
    Start-Sleep -seconds 10
    $WebBrowser.Refresh()
    $Form.ShowDialog()
}

I think I need to use the System.Windows.Forms.Timer class, but I'm not sure how to implement that into this example without any user interaction.

Anyone able to figure this out?


Solution

  • I got help with this from a user in Reddit, since the current answer provided here, specifically the first part of the answer, only confused me more.