Skip to content

Instantly share code, notes, and snippets.

@colin-haber
Last active July 29, 2021 00:40
Show Gist options
  • Save colin-haber/3ef16588c46419c1996496698c27331f to your computer and use it in GitHub Desktop.
Save colin-haber/3ef16588c46419c1996496698c27331f to your computer and use it in GitHub Desktop.
Minimize Spotify to tray on startup by running this script on login with Task Scheduler. Just make sure that Spotify is set to run on startup and close to tray. You may need to increase the sleep time parameter on line 65 if your Spotify window opens too slowly for the script to catch.
function Set-WindowState {
<# .LINK https://gist.github.com/Nora-Ballard/11240204 #>
[CmdletBinding(DefaultParameterSetName = 'InputObject')]
param(
[Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
[Object[]] $InputObject,
[Parameter(Position = 1)]
[ValidateSet('FORCEMINIMIZE', 'HIDE', 'MAXIMIZE', 'MINIMIZE', 'RESTORE',
'SHOW', 'SHOWDEFAULT', 'SHOWMAXIMIZED', 'SHOWMINIMIZED',
'SHOWMINNOACTIVE', 'SHOWNA', 'SHOWNOACTIVATE', 'SHOWNORMAL')]
[string] $State = 'SHOW'
)
Begin {
$WindowStates = @{
'FORCEMINIMIZE' = 11
'HIDE' = 0
'MAXIMIZE' = 3
'MINIMIZE' = 6
'RESTORE' = 9
'SHOW' = 5
'SHOWDEFAULT' = 10
'SHOWMAXIMIZED' = 3
'SHOWMINIMIZED' = 2
'SHOWMINNOACTIVE' = 7
'SHOWNA' = 8
'SHOWNOACTIVATE' = 4
'SHOWNORMAL' = 1
}
$Win32ShowWindowAsync = Add-Type -MemberDefinition @'
[DllImport("user32.dll")]
public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
'@ -Name "Win32ShowWindowAsync" -Namespace Win32Functions -PassThru
if (!$global:MainWindowHandles) {
$global:MainWindowHandles = @{ }
}
}
Process {
foreach ($process in $InputObject) {
if ($process.MainWindowHandle -eq 0) {
if ($global:MainWindowHandles.ContainsKey($process.Id)) {
$handle = $global:MainWindowHandles[$process.Id]
} else {
Write-Error "Main Window handle is '0'"
continue
}
} else {
$handle = $process.MainWindowHandle
$global:MainWindowHandles[$process.Id] = $handle
}
$Win32ShowWindowAsync::ShowWindowAsync($handle, $WindowStates[$State]) | Out-Null
Write-Verbose ("Set Window State '{1} on '{0}'" -f $MainWindowHandle, $State)
}
}
}
Write-Host "Waiting for Spotify to start..."
while ((Get-Process | Where-Object { $_.Name -eq "Spotify" }).Count -eq 0) {}
Start-Sleep 1
Get-Process Spotify | Set-WindowState -State Hide
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment