Humphrey
Humphrey

Reputation: 21

Is it possible to write a script to listen for screen resolution change in windows?

I'm trying to write a script, batch, powershell, vbs, whatever, that can listen for when a user changes the screen resolution so I can execute some code.

Is this possible?

Upvotes: 2

Views: 2448

Answers (2)

Darin
Darin

Reputation: 2368

PowerShell WinForms version of Brad Rem's C# code.

using namespace System.Windows.Forms
Add-Type -AssemblyName System.Windows.Forms

$InfoTextBox = [TextBox]@{
    Anchor = 'Top, Bottom, Left, Right'
    Font = 'Tahoma, 8.25pt'
    Location = '12, 12'
    Multiline = $true
    Name = 'InfoTextBox'
    Size = '460, 288'
    TabIndex = 1
}
$DisplaySettingsChangedForm = [Form]@{
    FormBorderStyle = 'Sizable'
    MinimumSize = '500, 350'
    Name = 'DisplaySettingsChangedForm'
    Size = '500, 350'
    StartPosition = 'CenterScreen'
    Text = 'Event: DisplaySettingsChanged'
    TopMost = $true
}

$DisplaySettingsChangedForm.Controls.Add($InfoTextBox);

[Microsoft.Win32.SystemEvents]::add_DisplaySettingsChanged({
    $AppendText = ''
    foreach ($Screen in [Screen]::AllScreens) {
        $InfoTextBox.Text +=  $AppendText +
            "Device Name: $($Screen.DeviceName)`r`n" +
            "Bounds: $($Screen.Bounds.ToString())`r`n" +
            "Type: $($Screen.GetType().ToString())`r`n" +
            "Working Area: $($Screen.WorkingArea.ToString())`r`n" +
            "Primary Screen: $($Screen.Primary.ToString())`r`n"
        $AppendText = "&`r`n"
    }
    $InfoTextBox.Text += "`r`n"
})

$null = $DisplaySettingsChangedForm.ShowDialog()

Upvotes: 1

JPBlanc
JPBlanc

Reputation: 72630

This seems to work :

PS> $sysevent = [microsoft.win32.systemevents]
PS> $sysevent

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    SystemEvents                             System.Object


PS> Register-ObjectEvent -InputObject $sysevent -EventName "DisplaySettingsChanged" -Action {[console]::Beep()}

Id              Name            State      HasMoreData     Location             Command
--              ----            -----      -----------     --------             -------
1               fa48b95f-299... NotStarted False                                [console]::Beep()

You can find the list of SytemEvents in Microsoft documentation.

DisplaySettingsChanged  Occurs when the user changes the display settings. 
DisplaySettingsChanging Occurs when the display settings are changing. 
EventsThreadShutdown    Occurs before the thread that listens for system events is terminated. 
InstalledFontsChanged   Occurs when the user adds fonts to or removes fonts from the system. 
LowMemory               Occurs when the system is running out of available RAM. 
PaletteChanged          Occurs when the user switches to an application that uses a different palette. 
PowerModeChanged        Occurs when the user suspends or resumes the system. 
SessionEnded            Occurs when the user is logging off or shutting down the system. 
SessionEnding           Occurs when the user is trying to log off or shut down the system. 
SessionSwitch           Occurs when the currently logged-in user has changed. 
TimeChanged             Occurs when the user changes the time on the system clock. 
TimerElapsed            Occurs when a windows timer interval has expired. 
UserPreferenceChanged   Occurs when a user preference has changed. 
UserPreferenceChanging  Occurs when a user preference is changing. 

To unregister event

PS> Unregister-Event -SubscriptionId 1

If you want to be able to distinguish Lock and Unlock the SessionSwitchEventHandler receives two parameters

  1. The source of the event.
  2. SessionSwitchEventArgs indicating the type of the session change event.

The SessionSwitchEventArgs own one propertie Reason which is an enum SessionSwitchReason values are :

ConsoleConnect        A session has been connected from the console.  
ConsoleDisconnect     A session has been disconnected from the console.  
RemoteConnect         A session has been connected from a remote connection.  
RemoteDisconnect      A session has been disconnected from a remote connection.  
SessionLogon          A user has logged on to a session.  
SessionLogoff         A user has logged off from a session.  
SessionLock           A session has been locked.  
SessionUnlock         A session has been unlocked.  
SessionRemoteControl  A session has changed its status to or from remote controlled mode.

Example :

PS> Register-ObjectEvent -InputObject $sysevent -EventName "SessionSwitch" -Action {[console]::Beep();Write-Host ($args[1]).Reason}

Id              Name            State      HasMoreData     Location             Command
--              ----            -----      -----------     --------             -------
9               20e6ecd4-fc0... NotStarted False                                [console]::Beep();fore...


PS >
SessionLock

SessionUnlock

If you want a list of events suscribed you can use Get-EventSubscriber :

SubscriptionId   : 5
SourceObject     : Microsoft.Win32.SystemEvents
EventName        : SessionSwitch
SourceIdentifier : 96fbabe4-518a-47b5-8a3f-bb89c68f7f39
Action           : System.Management.Automation.PSEventJob
HandlerDelegate  :
SupportEvent     : False
ForwardEvent     : False

Upvotes: 3

Related Questions