Using Pop-up Dialogs that Are Always Visible

by Jul 19, 2019

In the previous tip we used an old COM technique to display a pop-up box with a built-in timeout. That worked pretty well except that the dialog box can be covered under your PowerShell window at times.

With a little-known trick, you can make sure the dialog box will always open on top of all other windows:

$shell = New-Object -ComObject WScript.Shell
$value = $shell.Popup("You can't cover me!", 5, 'Example', 17 + 4096)

"Choice: $value"

Key is to add 4096 to the argument that controls buttons and icons. This turns the dialog into a system-modal dialog: it is guaranteed to open on top of all existing windows and can never be covered.

Using hash tables to wrap all these cryptic constants is again the way to go:

$timeoutSeconds = 5
$title = 'Example'
$message = "You can't cover me!"

$buttons = @{
  OK               = 0
  OkCancel         = 1  
  AbortRetryIgnore = 2
  YesNoCancel      = 3
  YesNo            = 4
  RetryCancel      = 5
}

$icon = @{
  Stop        = 16
  Question    = 32
  Exclamation = 48
  Information = 64
}

$clickedButton = @{
  -1 = 'Timeout'
  1  = 'OK'
  2  = 'Cancel'
  3  = 'Abort'
  4  = 'Retry'
  5  = 'Ignore'
  6  = 'Yes'
  7  = 'No'
}

$ShowOnTop = 4096

$shell = New-Object -ComObject WScript.Shell
$value = $shell.Popup($message, $timeoutSeconds, $title, $buttons.Ok + $icon.Exclamation + $ShowOnTop)

Switch ($clickedButton.$value)
{
  'OK'    { 'you clicked OK' }
  'Timeout'{ 'you did not click anything, timeout occurred' }
}  

Twitter This Tip! ReTweet this Tip!