How to display a HTML page in a PowerShell dialog?

Viewed 2094

I would like to display a simple HTML page in a PowerShell dialog box.

This is the way to build a dialog with dialog.ps1:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

$objForm = New-Object System.Windows.Forms.Form
[void] $objForm.ShowDialog()

In this windows I would like to display a webpage like index.html:

<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Title</title>
  </head>
  <body>
    Hello world!
  </body>
</html>

Of course, the webpage has a little more elements, like a picture with picturemap.

If this would work with CMD too, I would like this option even more.

1 Answers

The following snippet - which uses PSv5+[1] syntax for convenience - demonstrates use of the WebBrowser control to display HTML text in a WinForms dialog:

# PSv5+:
# Import namespaces so that types can be referred by
# their mere name (e.g., `Form` rather than `System.Windows.Forms.Form`)
#
using namespace System.Windows.Forms
using namespace System.Drawing

# Load the WinForms assembly.
Add-Type -AssemblyName System.Windows.Forms

# Create a form.
$form = [Form] @{
    ClientSize      = [Point]::new(400, 400)
    Text            = "WebBrowser-Control Demo"
}

# Create a web-browser control, make it as large as the inside of the form,
# and assign the HTML text.
$sb = [WebBrowser] @{
  ClientSize = $form.ClientSize
  DocumentText = @'
  <!DOCTYPE html>
  <html lang="de">
    <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Title</title>
    </head>
    <body>
      Hello world!
    </body>
  </html>
'@
}

# Add the web-browser control to the form...
$form.Controls.Add($sb)

# ... and display the form as a dialog (synchronously).
$form.ShowDialog()

# Clean up.
$form.Dispose()

[1] The code also works in PowerShell [Core] v7+, but not in PowerShell Core v6.x, because the latter fundamentally did not support WinForms (and WPF).

Related