Temporarily Locking the Screen

by Apr 15, 2013

PowerShell 3.0 uses .NET Framework 4.x so it has WPF (Windows Presentation Foundation) capabilities built-in. This way, it only takes a few lines of code to generate GUI elements.

Here's a sample function called Lock-Screen that places a transparent overlay window on top of your screen. You could use it to temporarily lock out user interaction, for example:

Function Lock-Screen
{
  param
  (
    $Title = 'Go away and come back in 10 seconds...',

    $Delay = 10
  )

  $window = New-Object Windows.Window
  $label = New-Object Windows.Controls.Label

  $label.Content = $Title
  $label.FontSize = 60
  $label.FontFamily = 'Consolas'
  $label.Background = 'Transparent'
  $label.Foreground = 'Red'
  $label.HorizontalAlignment = 'Center'
  $label.VerticalAlignment = 'Center'

  $Window.AllowsTransparency = $True
  $Window.Opacity = .7
  $window.WindowStyle = 'None'
  $window.Content = $label
  $window.Left = $window.Top = 0
  $window.WindowState = 'Maximized'
  $window.Topmost = $true

  $null = $window.Show()
  Start-Sleep -Seconds $Delay
  $window.Close()
}

To lock the screen, call Lock-Screen. By default, it will lock the screen for 10 seconds. Use the -Delay parameter to specify a different time interval.

The function simply sleeps while the screen is locked, but you could of course replace Start-Sleep with something more useful that you'd like to do while the screen is locked.

Twitter This Tip! ReTweet this Tip!