-
Notifications
You must be signed in to change notification settings - Fork 0
/
_Winamp-AutoRestartHelpers.ps1
3452 lines (3323 loc) · 166 KB
/
_Winamp-AutoRestartHelpers.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$WM_COMMAND = 0x0111
$WM_USER = 0x0400
function Logger {
param(
[Parameter()][ValidateSet('Error', 'Warning', 'Information', 'Debug', 'Verbose')][string]$LogLevel,
[Parameter(Mandatory)][string]$Message
)
$Timestamp = Get-Date -Format 'yyyMMdd-HHmmss'
switch ($LogLevel) {
'Information' {
# Workaround for https://stackoverflow.com/questions/55191548/write-information-does-not-show-in-a-file-transcribed-by-start-transcript
Write-Information "${Timestamp}: $Message"
[System.Console]::WriteLine("INFO: ${Timestamp}: $Message")
}
'Debug' {
Write-Debug "${Timestamp}: $Message"
}
'Verbose' {
Write-Verbose "${Timestamp}: $Message"
}
'Error' {
Write-Error "${Timestamp}: $Message"
}
'Warning' {
Write-Warning "${Timestamp}: $Message"
}
}
}
Function Get-Timestamp {
<#
.VERSION 20230407
#>
return Get-Date -Format 'yyyyMMdd-HHmmss'
}
function Wait-WinampInit {
<#
.VERSION 2023.03.30
.SYNOPSIS
Wait until the Winamp API is ready to accept commands
#>
param(
$window
)
$StartTime = Get-Date
$process = Get-Process 'winamp' -ErrorAction SilentlyContinue
if ($process.Count -ne 1) {
Logger -LogLevel Debug 'Waiting for the Winamp process to start..'
[System.Console]::Write('Waiting for Winamp to start.')
while ($process.Count -ne 1) {
try {
$process = Get-Process 'winamp' -ErrorAction SilentlyContinue
}
catch {
}
Start-Sleep -Seconds 1
[System.Console]::Write('.')
}
[System.Console]::WriteLine(': ok')
}
if ($window.ClassName -ne 'Winamp v1.x') {
Logger -LogLevel Debug 'Waiting for the Winamp 1.x class to initialize..'
[System.Console]::Write('Waiting for the Winamp 1.x class to load.')
while ($window.ClassName -ne 'Winamp v1.x') {
try {
$window = [System.Windows.Win32Window]::FromProcessName('winamp')
}
catch {
}
if ($process.HasExited) {
[System.Console]::Write(': failed!')
Throw 'Winamp exited unexpectedly.'
}
Start-Sleep -Seconds 1
[System.Console]::Write('.')
}
[System.Console]::WriteLine(': ok')
}
[System.Console]::Write('Waiting for the API to be ready.')
do {
if ($process.HasExited) {
[System.Console]::Write(': failed!')
Throw 'Winamp exited unexpectedly.'
}
$SeekPosMS = $window.SendMessage($WM_USER, 0, 105)
[System.Console]::Write('.')
Start-Sleep -Seconds 1
} while (!([long]$SeekPosMS -gt 0))
$Duration = (Get-Date) - $StartTime
[System.Console]::WriteLine(": ok (SeekPosMS:$SeekPosMS)")
Logger -LogLevel Debug "Winamp API ready. SeekPosMS: $SeekPosMS. Duration: $Duration"
return $window | Where-Object ClassName -EQ 'Winamp v1.x'
}
function Get-WinampStatus {
param(
[Parameter(Mandatory = $true)]$Window
)
$playStatus = Get-WinampPlayStatus -Window $Window
$SeekPosMS = Get-WinampSeekPos -Window $Window
$PlaylistIndex = Get-WinampPlaylistIndex -Window $Window
$fingerprint = "hWnd=$($window.hWnd);status=$playStatus;ix=$PlaylistIndex;seek=$SeekPosMS"
return @{
hWnd = $window.hWnd
PlayStatus = $playStatus
SeekPosMS = $SeekPosMS
Fingerprint = $fingerprint
StartTime = $window.Process.StartTime
Timestamp = Get-Date
Tainted = $false
}
}
function Restart-Winamp {
# https://forums.winamp.com/forum/developer-center/winamp-development/156726-winamp-application-programming-interface?postid=1953663
param(
[Parameter(Mandatory = $true)]$Window
)
$WM_COMMAND = 0x0111
$WM_USER = 0x0400
$playStatus = $window.SendMessage($WM_USER, 0, 104) # 0: stopped, 1: playing, 3: paused
$SeekPosMS = $window.SendMessage($WM_USER, 0, 105)
Logger -LogLevel Debug "Winamp: hWnd: $($window.hWnd), PlayStatus: $playStatus, SeekPos: $SeekPosMS"
Logger -LogLevel Information 'RESTARTING Winamp..'
$process = Get-Process 'winamp'
$window.SendMessage($WM_USER, 0, 135) | Out-Null
While (!$process.HasExited) {
Start-Sleep 1
}
$process = Get-Process 'winamp'
$window = Wait-WinampInit
Logger -LogLevel Information "Winamp restarted: hWnd: $($window.hWnd), PlayStatus: $playStatus, SeekPos: $SeekPosMS"
switch ($playStatus) {
1 {
Invoke-WinampPlay -Window $window | Out-Null
Logger -LogLevel Debug "Seeking to previous pos: $seekPosMS ms"
Set-WinampSeekPos -Window $window -SeekPosMS $SeekPosMS | Out-Null
$window.SendMessage($WM_USER, $SeekPosMS, 106) | Out-Null
}
3 {
Invoke-WinampPlay -Window $window | Out-Null
Logger -LogLevel Debug "Seeking to previous pos: $seekPosMS ms"
Set-WinampSeekPos -Window $window -SeekPosMS $SeekPosMS | Out-Null
Invoke-WinampPause -Window $window | Out-Null
}
}
return $window
}
#######
function Get-WinampSeekPos {
param(
[Parameter(Mandatory = $true)]$Window
)
# [long]$SeekPosMS = ExponentialBackoff -Rounds 3 -InitialDelayMs 100 -Do {
# $window.SendMessage($WM_USER, 0, 105)
# } -Check {
# $result -gt 0 ## Not implemented yet in ExponentialBackoff
# }
# [long]$SeekPosMS = $window.SendMessage($WM_USER, 0, 105)
# while ($SeekPosMS -eq 0) {
# Start-Sleep 1
# $SeekPosMS = $window.SendMessage($WM_USER, 0, 105)
# }
$SeekPosMS = ExponentialBackoff `
-Do { $window.SendMessage($WM_USER, 0, 105) } `
-Check { [long]$DoResult -gt 0 }
return [long]$SeekPosMS.DoResult
}
function Get-WinampPlayStatus {
<#
0: stopped, 1: playing, 3: paused
#>
param(
[Parameter(Mandatory = $true)]$Window
)
$playStatus = $window.SendMessage($WM_USER, 0, 104)
return $playStatus
}
function Invoke-WinampPause {
param(
[Parameter(Mandatory = $true)]$Window
)
Logger -LogLevel Information 'Pressing: PLAY'
$result = ExponentialBackoff `
-Do { $window.SendMessage($WM_COMMAND, 40046, 0) } `
-Check { (Get-WinampPlayStatus -Window $Window) -eq 3 }
return $result.CheckResult
}
function Invoke-WinampPlay {
param(
[Parameter(Mandatory = $true)]$Window
)
Logger -LogLevel Information 'Pressing: PAUSE'
$result = ExponentialBackoff `
-Do { $window.SendMessage($WM_COMMAND, 40045, 0) } `
-Check { (Get-WinampPlayStatus -Window $Window) -eq 1 }
return $result.CheckResult
}
function Invoke-WinampRestart {
param(
[Parameter(Mandatory = $true)]$Window
)
Logger -LogLevel Information 'RESTARTING Winamp..'
$result = $window.SendMessage($WM_USER, 0, 135)
return $result
}
function Set-WinampPlaylistIndex {
param(
[Parameter(Mandatory = $true)]$Window,
[Parameter(Mandatory = $true)][int]$PlaylistIndex # Starts at 1
)
Logger -LogLevel Information "Seeking to Playlist index: $($PlaylistIndex)"
$result = ExponentialBackoff `
-Do { $window.SendMessage($WM_USER, $PlaylistIndex - 1, 121) } `
-Check { (Get-WinampPlaylistIndex -Window $Window) -eq $PlaylistIndex }
return $result.DoResult + 1
}
function Get-WinampPlaylistIndex {
param(
[Parameter(Mandatory = $true)]$Window
)
$result = $window.SendMessage($WM_USER, 0, 125)
return $result + 1
}
function Set-WinampSeekPos {
param(
[Parameter(Mandatory = $true)]$Window,
[Parameter(Mandatory = $true)][long]$SeekPosMS
)
Logger -LogLevel Information "Seeking track to time(ms): $($SeekPosMS)"
$result = ExponentialBackoff `
-Do { $window.SendMessage($WM_USER, $SeekPosMS, 106) } `
-Check { [long]$test = Get-WinampSeekPos -Window $Window; ([Math]::Abs($SeekPosMS - $test) -lt 2000) }
return $result.CheckResult
}
function Get-WinampSongTitle {
<#
.VERSION 2023.11.25
.SYNOPSIS
Returns the title of the currently selected song in Winamp.
#>
[CmdletBinding()]
param(
)
$DebugPreference = 'SilentlyContinue'
if ($PSBoundParameters.ContainsKey('Debug')) {
$DebugPreference = 'Continue'
}
$VerbosePreference = 'SilentlyContinue'
if ($PSBoundParameters.ContainsKey('Verbose')) {
$VerbosePreference = 'Continue'
}
$wpid = Get-Process winamp -ErrorAction SilentlyContinue
if (!$wpid) {
Write-Debug 'Winamp not running.'
return $null
}
if ($wpid.Count -gt 1) {
if ($ErrorActionPreference -eq 'SilentlyContinue') {
return $null
}
Throw "Multiple Winamp processes found; PIDs: $($wpid | Select-Object -ExpandProperty Id)"
}
$wTitles = @()
[WinAPI]::GetProcessWindows($wpid.Id, [ref]$wTitles) | Out-Null
$Search = $wTitles | Select-String '- Winamp' | Select-Object -Last 1
if (!$Search) {
if ($ErrorActionPreference -eq 'SilentlyContinue') {
return $null
}
Throw 'Winamp song info not found in window titles.'
}
$Title = $Search.ToString()
$Title = $Title -replace '★', ''
$Title = $Title -replace '\s*\[(?:Stopped|Paused)\]$'
$Title = $Title -replace '^\d+\.\s*', ''
$Title = $Title -replace '\s*\-\s*Winamp$', ''
return $Title
}
function Get-WinampSongRating {
<#
.VERSION 2023.11.18
.SYNOPSIS
Gets the rating of the currently playing song in Winamp.
.DESCRIPTION
The function counts the number of stars in the title of the Winamp window.
#>
[CmdletBinding()]
param(
)
$DebugPreference = 'SilentlyContinue'
if ($PSBoundParameters.ContainsKey('Debug')) {
$DebugPreference = 'Continue'
}
$VerbosePreference = 'SilentlyContinue'
if ($PSBoundParameters.ContainsKey('Verbose')) {
$VerbosePreference = 'Continue'
}
$wpid = Get-Process winamp -ErrorAction SilentlyContinue
if (!$wpid) {
Write-Debug 'Winamp not running.'
return $null
}
if ($wpid.Count -gt 1) {
Throw "Multiple Winamp processes found; PIDs: $($wpid | Select-Object -ExpandProperty Id)"
}
$rating = $null
$wTitles = @()
[WinAPI]::GetProcessWindows($wpid.Id, [ref]$wTitles) | Out-Null
# There are two titles that contain the rating, but one is not instantly updated when the rating changes.
# The safest way to get the rating is (Get-Process winamp).MainWindowTitle but that's not available when the "Now playing notifier" pops up.
$search = $wTitles | Select-String "($([char]0x2605)+)?\s*\-\s*Winamp" | Select-Object -Last 1
if (!$search) {
Write-Debug 'Winamp song info not found in window titles.'
return $null
}
Write-Debug "Search result: $($search.ToString())"
Write-Verbose "Search groups: $($search.Matches.Groups | Out-String)"
$rating = $search.Matches.Groups[1].Value.Length
return $rating
}
Function ExponentialBackoff {
<#
.VERSION 20230408
#>
param(
[int]$Rounds = 5,
[int]$InitialDelayMs = 100,
[scriptblock]$Do = {},
[scriptblock]$Check = {}
)
$CheckResult = $null
for ($round = 1; $round -le $rounds; $round++) {
if ($round -gt 1) {
Write-Verbose "Check condition not met, retrying with exponential backoff, round $round. Sleeping for $InitialDelayMs ms.."
Start-Sleep -Milliseconds $InitialDelayMs
$InitialDelayMs *= 2
}
try {
$DoResult = & $Do
$DoSuccess = $true
}
catch {
$DoSuccess = $false
}
# If a Check block was provided, success depends if the Check block returns $true.
if ($Check.ToString()) {
$CheckResult = & $Check
if (!$CheckResult) {
Continue
}
}
else {
# If no Check block was provided, success depends if the Do block doesn't throw an error.
if (!$DoSuccess) {
Continue
}
}
Write-Verbose 'Check condition met, exiting loop.'
return @{DoResult = $DoResult; CheckResult = $CheckResult }
}
Throw "Check condition not met after $Rounds rounds."
}
#######
###
#Region Register-PowerShellScheduledTask
###
function Register-PowerShellScheduledTask {
<#
.VERSION 20230407
.SYNOPSIS
Registers a PowerShell script as a **Hidden** Scheduled Task.
At the moment the schedule frequency is hardcoded to every 15 minutes.
.DESCRIPTION
Currently, it's not possible create a hidden Scheduled Task that executes a PowerShell task.
A command window will keep popping up every time the task is run.
This function creates a wrapper vbs script that runs the PowerShell script as hidden.
source: https://github.com/PowerShell/PowerShell/issues/3028
.PARAMETER ScriptPath
The path to the PowerShell script that will be executed in the task.
.PARAMETER Parameters
A hashtable of parameters to pass to the script.
.PARAMETER TaskName
The Scheduled Task will be registered under this name in the Task Scheduler.
If not specified, the script name will be used.
.PARAMETER AllowRunningOnBatteries
Allows the task to run when the computer is on batteries.
.PARAMETER Uninstall
Unregister the Scheduled Task.
.PARAMETER ExecutionTimeLimit
The maximum amount of time the task is allowed to run.
New-TimeSpan -Hours 72
New-TimeSpan -Minutes 15
New-TimeSpan -Seconds 30
New-TimeSpan -Seconds 0 = Means disabled
.PARAMETER AsAdmin
Run the Scheduled Task as administrator.
.PARAMETER GroupId
The Scheduled Task will be registered under this group in the Task Scheduler.
Eg: "BUILTIN\Administrators"
.PARAMETER TimeInterval
The Scheduled Task will be run every X minutes.
.PARAMETER AtLogon
The Scheduled Task will be run at user logon.
.PARAMETER AtStartup
The Scheduled Task will be run at system startup. Requires admin rights.
#>
param(
[Parameter(Mandatory = $true, Position = 0)]$ScriptPath,
[hashtable]$Parameters = @{},
[string]$TaskName,
[int]$TimeInterval,
[switch]$AtLogon,
[switch]$AtStartup,
[bool]$AllowRunningOnBatteries,
[switch]$DisallowHardTerminate,
[TimeSpan]$ExecutionTimeLimit,
[string]$GroupId,
[switch]$AsAdmin,
[switch]$Uninstall
)
if (!($TimeInterval -or $AtLogon -or $AtStartup -or $Uninstall)) {
Throw 'At least one of the following parameters must be defined: -TimeInterval, -AtLogon, -AtStartup, (or -Uninstall)'
}
if ([string]::IsNullOrEmpty($TaskName)) {
$TaskName = Split-Path $ScriptPath -Leaf
}
## Uninstall
if ($Uninstall) {
Stop-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
# Return $true if no tasks found, otherwise $false
return !(Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue)
}
## Install
if (!(Test-Path $ScriptPath)) {
Throw "Script ``$ScriptPath`` not found!"
}
$ScriptPath = Resolve-Path -LiteralPath $ScriptPath
# Create wrapper vbs script so we can run the PowerShell script as hidden
# https://github.com/PowerShell/PowerShell/issues/3028
if ($GroupId) {
$vbsPath = "$env:ALLUSERSPROFILE\PsScheduledTasks\$TaskName.vbs"
}
else {
$vbsPath = "$env:LOCALAPPDATA\PsScheduledTasks\$TaskName.vbs"
}
$vbsDir = Split-Path $vbsPath -Parent
if (!(Test-Path $vbsDir)) {
New-Item -ItemType Directory -Path $vbsDir
}
$ps = @(); $Parameters.GetEnumerator() | ForEach-Object { $ps += "-$($_.Name) $($_.Value)" }; $ps -join ' '
$vbsScript = @"
Dim shell,command
command = "powershell.exe -nologo -File $ScriptPath $ps"
Set shell = CreateObject("WScript.Shell")
shell.Run command, 0, true
"@
Set-Content -Path $vbsPath -Value $vbsScript -Force
Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue -OutVariable TaskExists
if ($TaskExists.State -eq 'Running') {
Write-Debug "Stopping task for update: $TaskName"
$TaskExists | Stop-ScheduledTask
}
$action = New-ScheduledTaskAction -Execute $vbsPath
## Schedule
$triggers = @()
if ($TimeInterval) {
$t1 = New-ScheduledTaskTrigger -Daily -At 00:05
$t2 = New-ScheduledTaskTrigger -Once -At 00:05 `
-RepetitionInterval (New-TimeSpan -Minutes $TimeInterval) `
-RepetitionDuration (New-TimeSpan -Hours 23 -Minutes 55)
$t1.Repetition = $t2.Repetition
$t1.Repetition.StopAtDurationEnd = $false
$triggers += $t1
}
if ($AtLogOn) {
$triggers += New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
}
if ($AtStartUp) {
$triggers += New-ScheduledTaskTrigger -AtStartup
}
## Additional Options
$AdditionalOptions = @{}
if ($AsAdmin) {
$AdditionalOptions.RunLevel = 'Highest'
}
if ($GroupId) {
$STPrin = New-ScheduledTaskPrincipal -GroupId $GroupId
$AdditionalOptions.Principal = $STPrin
}
## Settings
$AdditionalSettings = @{}
if ($AllowRunningOnBatteries -eq $true) {
$AdditionalSettings.AllowStartIfOnBatteries = $true
$AdditionalSettings.DontStopIfGoingOnBatteries = $true
}
elseif ($AllowRunningOnBatteries -eq $false) {
$AdditionalSettings.AllowStartIfOnBatteries = $false
$AdditionalSettings.DontStopIfGoingOnBatteries = $false
}
if ($DisallowHardTerminate) {
$AdditionalSettings.DisallowHardTerminate = $true
}
if ($ExecutionTimeLimit) {
$AdditionalSettings.ExecutionTimeLimit = $ExecutionTimeLimit
}
$STSet = New-ScheduledTaskSettingsSet `
-MultipleInstances IgnoreNew `
@AdditionalSettings
## Decide if Register or Update
if (!$TaskExists) {
$cim = Register-ScheduledTask -Action $action -Trigger $triggers -TaskName $TaskName -Description "Scheduled Task for running $ScriptPath" -Settings $STSet @AdditionalOptions
}
else {
$cim = Set-ScheduledTask -TaskName $TaskName -Action $action -Trigger $triggers -Settings $STSet @AdditionalOptions
}
# Sometimes $cim returns more than 1 object, looks like a PowerShell bug.
# In those cases, get the last element of the list.
return $cim
}
###
#Endregion
###
###
#Region GetWindowTiles
###
Add-Type -Language CSharp -TypeDefinition @'
using System;
using System.Text;
using System.Runtime.InteropServices;
public class WinAPI
{
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
public static bool GetProcessWindows(int processId, out string[] windowTitles)
{
var list = new System.Collections.Generic.List<string>();
EnumWindows((hWnd, lParam) =>
{
int pid = 0;
if (GetWindowThreadProcessId(hWnd, out pid) != 0 && pid == processId)
{
var titleBuilder = new StringBuilder(256);
GetWindowText(hWnd, titleBuilder, titleBuilder.Capacity);
list.Add(titleBuilder.ToString());
}
return true;
}, IntPtr.Zero);
windowTitles = list.ToArray();
return true;
}
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
}
'@
###
#Region Control-WinApps.ps1
###
# Copyright (c) 2014 Serguei Kouzmine
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
<#
.SYNOPSIS
Low Level Win32 API calls to control a windows app
.EXAMPLE
Get Winamp Play/Stop status:
$window = [System.Windows.Win32Window]::FromProcessName("winamp")
$window.SendMessage(0x0400,0,104)
# ref: https://forums.winamp.com/forum/developer-center/winamp-development/156726-winamp-application-programming-interface?postid=1953663
.LINK
source: https://github.com/sergueik/powershell_selenium/blob/master/powershell/button_selenium.ps1
ref: http://www.codeproject.com/Articles/790966/Hosting-And-Changing-Controls-In-Other-Application
#>
Add-Type -TypeDefinition @'
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Collections;
using System.Drawing.Imaging;
namespace System.Windows
{
class Win32WindowEvents
{
delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("user32.dll")]
static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
[DllImport("user32.dll")]
static extern bool UnhookWinEvent(IntPtr hWinEventHook);
static IntPtr hhook;
// Need to ensure delegate is not collected while we're using it,
// storing it in a class field is simplest way to do this.
static WinEventDelegate procDelegate = new WinEventDelegate(WinEventProc);
public static void StartListening()
{
hhook = SetWinEventHook((uint)EventTypes.EVENT_MIN, (uint)EventTypes.EVENT_MAX, IntPtr.Zero,
procDelegate, 0, 0, (uint)(WinHookParameter.OUTOFCONTEXT | WinHookParameter.SKIPOWNPROCESS));
}
static void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
Win32Window Window = new Win32Window(hwnd);
//if window is found fire event
if (predicate != null && predicate.Invoke(Window) == true)
{
WindowFound(Window.Process, Window, (EventTypes)eventType);
predicate = null;
StopListening();
}
if (GlobalWindowEvent != null)
{
GlobalWindowEvent(Window.Process, Window, (EventTypes)eventType);
}
}
static Func<Win32Window, bool> predicate;
public static void WaitForWindowWhere(Func<Win32Window, bool> Predicate)
{
predicate = Predicate;
StartListening();
}
public static void StopListening()
{
UnhookWinEvent(hhook);
}
public delegate void WinEvent(Process Process, Win32Window Window, EventTypes type);
public static event WinEvent WindowFound = delegate { };
public static event WinEvent GlobalWindowEvent;
[Flags]
internal enum WinHookParameter : uint
{
INCONTEXT = 4,
OUTOFCONTEXT = 0,
SKIPOWNPROCESS = 2,
SKIPOWNTHREAD = 1
}
public enum EventTypes : uint
{
WINEVENT_OUTOFCONTEXT = 0x0000, // Events are ASYNC
WINEVENT_SKIPOWNTHREAD = 0x0001, // Don't call back for events on installer's thread
WINEVENT_SKIPOWNPROCESS = 0x0002, // Don't call back for events on installer's process
WINEVENT_INCONTEXT = 0x0004, // Events are SYNC, this causes your dll to be injected into every process
EVENT_MIN = 0x00000001,
EVENT_MAX = 0x7FFFFFFF,
EVENT_SYSTEM_SOUND = 0x0001,
EVENT_SYSTEM_ALERT = 0x0002,
EVENT_SYSTEM_FOREGROUND = 0x0003,
EVENT_SYSTEM_MENUSTART = 0x0004,
EVENT_SYSTEM_MENUEND = 0x0005,
EVENT_SYSTEM_MENUPOPUPSTART = 0x0006,
EVENT_SYSTEM_MENUPOPUPEND = 0x0007,
EVENT_SYSTEM_CAPTURESTART = 0x0008,
EVENT_SYSTEM_CAPTUREEND = 0x0009,
EVENT_SYSTEM_MOVESIZESTART = 0x000A,
EVENT_SYSTEM_MOVESIZEEND = 0x000B,
EVENT_SYSTEM_CONTEXTHELPSTART = 0x000C,
EVENT_SYSTEM_CONTEXTHELPEND = 0x000D,
EVENT_SYSTEM_DRAGDROPSTART = 0x000E,
EVENT_SYSTEM_DRAGDROPEND = 0x000F,
EVENT_SYSTEM_DIALOGSTART = 0x0010,
EVENT_SYSTEM_DIALOGEND = 0x0011,
EVENT_SYSTEM_SCROLLINGSTART = 0x0012,
EVENT_SYSTEM_SCROLLINGEND = 0x0013,
EVENT_SYSTEM_SWITCHSTART = 0x0014,
EVENT_SYSTEM_SWITCHEND = 0x0015,
EVENT_SYSTEM_MINIMIZESTART = 0x0016,
EVENT_SYSTEM_MINIMIZEEND = 0x0017,
EVENT_SYSTEM_DESKTOPSWITCH = 0x0020,
EVENT_SYSTEM_END = 0x00FF,
EVENT_OEM_DEFINED_START = 0x0101,
EVENT_OEM_DEFINED_END = 0x01FF,
EVENT_UIA_EVENTID_START = 0x4E00,
EVENT_UIA_EVENTID_END = 0x4EFF,
EVENT_UIA_PROPID_START = 0x7500,
EVENT_UIA_PROPID_END = 0x75FF,
EVENT_CONSOLE_CARET = 0x4001,
EVENT_CONSOLE_UPDATE_REGION = 0x4002,
EVENT_CONSOLE_UPDATE_SIMPLE = 0x4003,
EVENT_CONSOLE_UPDATE_SCROLL = 0x4004,
EVENT_CONSOLE_LAYOUT = 0x4005,
EVENT_CONSOLE_START_APPLICATION = 0x4006,
EVENT_CONSOLE_END_APPLICATION = 0x4007,
EVENT_CONSOLE_END = 0x40FF,
EVENT_OBJECT_CREATE = 0x8000, // hwnd ID idChild is created item
EVENT_OBJECT_DESTROY = 0x8001, // hwnd ID idChild is destroyed item
EVENT_OBJECT_SHOW = 0x8002, // hwnd ID idChild is shown item
EVENT_OBJECT_HIDE = 0x8003, // hwnd ID idChild is hidden item
EVENT_OBJECT_REORDER = 0x8004, // hwnd ID idChild is parent of zordering children
EVENT_OBJECT_FOCUS = 0x8005, // hwnd ID idChild is focused item
EVENT_OBJECT_SELECTION = 0x8006, // hwnd ID idChild is selected item (if only one), or idChild is OBJID_WINDOW if complex
EVENT_OBJECT_SELECTIONADD = 0x8007, // hwnd ID idChild is item added
EVENT_OBJECT_SELECTIONREMOVE = 0x8008, // hwnd ID idChild is item removed
EVENT_OBJECT_SELECTIONWITHIN = 0x8009, // hwnd ID idChild is parent of changed selected items
EVENT_OBJECT_STATECHANGE = 0x800A, // hwnd ID idChild is item w/ state change
EVENT_OBJECT_LOCATIONCHANGE = 0x800B, // hwnd ID idChild is moved/sized item
EVENT_OBJECT_NAMECHANGE = 0x800C, // hwnd ID idChild is item w/ name change
EVENT_OBJECT_DESCRIPTIONCHANGE = 0x800D, // hwnd ID idChild is item w/ desc change
EVENT_OBJECT_VALUECHANGE = 0x800E, // hwnd ID idChild is item w/ value change
EVENT_OBJECT_PARENTCHANGE = 0x800F, // hwnd ID idChild is item w/ new parent
EVENT_OBJECT_HELPCHANGE = 0x8010, // hwnd ID idChild is item w/ help change
EVENT_OBJECT_DEFACTIONCHANGE = 0x8011, // hwnd ID idChild is item w/ def action change
EVENT_OBJECT_ACCELERATORCHANGE = 0x8012, // hwnd ID idChild is item w/ keybd accel change
EVENT_OBJECT_INVOKED = 0x8013, // hwnd ID idChild is item invoked
EVENT_OBJECT_TEXTSELECTIONCHANGED = 0x8014, // hwnd ID idChild is item w? test selection change
EVENT_OBJECT_CONTENTSCROLLED = 0x8015,
EVENT_SYSTEM_ARRANGMENTPREVIEW = 0x8016,
EVENT_OBJECT_END = 0x80FF,
EVENT_AIA_START = 0xA000,
EVENT_AIA_END = 0xAFFF,
}
}
public static class WinAPI
{
#region Pinvoke
[DllImport("user32.dll", SetLastError = true)]
static extern System.UInt16 RegisterClassW([System.Runtime.InteropServices.In] ref WNDCLASS lpWndClass);
[Flags]
public enum WindowStyles : uint
{
WS_OVERLAPPED = 0x00000000,
WS_POPUP = 0x80000000,
WS_CHILD = 0x40000000,
WS_MINIMIZE = 0x20000000,
WS_VISIBLE = 0x10000000,
WS_DISABLED = 0x08000000,
WS_CLIPSIBLINGS = 0x04000000,
WS_CLIPCHILDREN = 0x02000000,
WS_MAXIMIZE = 0x01000000,
WS_BORDER = 0x00800000,
WS_DLGFRAME = 0x00400000,
WS_VSCROLL = 0x00200000,
WS_HSCROLL = 0x00100000,
WS_SYSMENU = 0x00080000,
WS_THICKFRAME = 0x00040000,
WS_GROUP = 0x00020000,
WS_TABSTOP = 0x00010000,
WS_MINIMIZEBOX = 0x00020000,
WS_MAXIMIZEBOX = 0x00010000,
WS_CAPTION = WS_BORDER | WS_DLGFRAME,
WS_TILED = WS_OVERLAPPED,
WS_ICONIC = WS_MINIMIZE,
WS_SIZEBOX = WS_THICKFRAME,
WS_TILEDWINDOW = WS_OVERLAPPEDWINDOW,
WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,
WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU,
WS_CHILDWINDOW = WS_CHILD,
BS_RADIOBUTTON = 0x00000004,
BS_CHECKBOX = 0x00000002,
ES_MULTILINE =0x0004,
ES_AUTOVSCROLL = 0x0040,
ES_AUTOHSCROLL = 0x0080,
ES_WANTRETURN = 0x1000,
ES_LEFT =0x0000,
LBS_NOTIFY=0x0001,
LBS_SORT=0x0002,
LBS_STANDARD= LBS_NOTIFY | LBS_SORT | WS_VSCROLL | WS_BORDER,
SBS_HORZ=0x0000,
SBS_VERT=0x0001
/*
#define SBS_HORZ 0x0000L
#define SBS_VERT 0x0001L
#define SBS_TOPALIGN 0x0002L
#define SBS_LEFTALIGN 0x0002L
#define SBS_BOTTOMALIGN 0x0004L
#define SBS_RIGHTALIGN 0x0004L
#define SBS_SIZEBOXTOPLEFTALIGN 0x0002L
#define SBS_SIZEBOXBOTTOMRIGHTALIGN 0x0004L
#define SBS_SIZEBOX 0x0008L
* /
/*
#define LBS_NOTIFY 0x0001L
#define LBS_SORT 0x0002L
#define LBS_NOREDRAW 0x0004L
#define LBS_MULTIPLESEL 0x0008L
#define LBS_OWNERDRAWFIXED 0x0010L
#define LBS_OWNERDRAWVARIABLE 0x0020L
#define LBS_HASSTRINGS 0x0040L
#define LBS_USETABSTOPS 0x0080L
#define LBS_NOINTEGRALHEIGHT 0x0100L
#define LBS_MULTICOLUMN 0x0200L
#define LBS_WANTKEYBOARDINPUT 0x0400L
#define LBS_EXTENDEDSEL 0x0800L
#define LBS_DISABLENOSCROLL 0x1000L
#define LBS_NODATA 0x2000L
*/
/*
#define ES_LEFT 0x0000L
#define ES_CENTER 0x0001L
#define ES_RIGHT 0x0002L
#define ES_MULTILINE 0x0004L
#define ES_UPPERCASE 0x0008L
#define ES_LOWERCASE 0x0010L
#define ES_PASSWORD 0x0020L
#define ES_AUTOVSCROLL 0x0040L
#define ES_AUTOHSCROLL 0x0080L
#define ES_NOHIDESEL 0x0100L
#define ES_OEMCONVERT 0x0400L
#define ES_READONLY 0x0800L
#define ES_WANTRETURN 0x1000L
*/
/*
#define BS_PUSHBUTTON 0x00000000L
#define BS_DEFPUSHBUTTON 0x00000001L
#define BS_CHECKBOX 0x00000002L
#define BS_AUTOCHECKBOX 0x00000003L
#define
#define BS_3STATE 0x00000005L
#define BS_AUTO3STATE 0x00000006L
#define BS_GROUPBOX 0x00000007L
#define BS_USERBUTTON 0x00000008L
#define BS_AUTORADIOBUTTON 0x00000009L
#define BS_PUSHBOX 0x0000000AL
#define BS_OWNERDRAW 0x0000000BL
#define BS_TYPEMASK 0x0000000FL
#define BS_LEFTTEXT 0x00000020L
#if(WINVER >= 0x0400)
#define BS_TEXT 0x00000000L
#define BS_ICON 0x00000040L
#define BS_BITMAP 0x00000080L
#define BS_LEFT 0x00000100L
#define BS_RIGHT 0x00000200L
#define BS_CENTER 0x00000300L
#define BS_TOP 0x00000400L
#define BS_BOTTOM 0x00000800L
#define BS_VCENTER 0x00000C00L
#define BS_PUSHLIKE 0x00001000L
#define BS_MULTILINE 0x00002000L
#define BS_NOTIFY 0x00004000L
#define BS_FLAT 0x00008000L
#define BS_RIGHTBUTTON BS_LEFTTEXT
*/
}
[Flags]
public enum WindowStylesEx : uint
{
//Extended Window Styles
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_NOPARENTNOTIFY = 0x00000004,
WS_EX_TOPMOST = 0x00000008,
WS_EX_ACCEPTFILES = 0x00000010,
WS_EX_TRANSPARENT = 0x00000020,
//#if(WINVER >= 0x0400)
WS_EX_MDICHILD = 0x00000040,
WS_EX_TOOLWINDOW = 0x00000080,
WS_EX_WINDOWEDGE = 0x00000100,
WS_EX_CLIENTEDGE = 0x00000200,
WS_EX_CONTEXTHELP = 0x00000400,
WS_EX_RIGHT = 0x00001000,
WS_EX_LEFT = 0x00000000,
WS_EX_RTLREADING = 0x00002000,
WS_EX_LTRREADING = 0x00000000,
WS_EX_LEFTSCROLLBAR = 0x00004000,
WS_EX_RIGHTSCROLLBAR = 0x00000000,
WS_EX_CONTROLPARENT = 0x00010000,
WS_EX_STATICEDGE = 0x00020000,
WS_EX_APPWINDOW = 0x00040000,
WS_EX_OVERLAPPEDWINDOW = (WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE),
WS_EX_PALETTEWINDOW = (WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST),
//#endif /* WINVER >= 0x0400 */
//#if(WIN32WINNT >= 0x0500)
WS_EX_LAYERED = 0x00080000,
//#endif /* WIN32WINNT >= 0x0500 */
//#if(WINVER >= 0x0500)
WS_EX_NOINHERITLAYOUT = 0x00100000, // Disable inheritence of mirroring by children
WS_EX_LAYOUTRTL = 0x00400000, // Right to left mirroring
//#endif /* WINVER >= 0x0500 */
//#if(WIN32WINNT >= 0x0500)