トップレベルウィンドウのハンドルを Z オーダー順に列挙します。
Ps1
1Add-Type -TypeDefinition @"
2using System;
3using System.Runtime.InteropServices;
4
5public class Platform
6{
7 [DllImport("user32.dll", SetLastError = true)]
8 public static extern IntPtr GetWindow(IntPtr hwnd, GetWindowType uCmd);
9
10 [DllImport("user32.dll", SetLastError = true)]
11 public static extern IntPtr GetDesktopWindow();
12}
13
14public enum GetWindowType : uint
15{
16 First = 0,
17 Last = 1,
18 Next = 2,
19 Prev = 3,
20 Owner = 4,
21 Child = 5,
22 EnabledPopup = 6
23}
24"@
25$window = [Platform]::GetWindow([Platform]::GetDesktopWindow(), [GetWindowType]::Child)
26while ($window -ne [IntPtr]::Zero)
27{
28 $window
29 $window = [Platform]::GetWindow($window, [GetWindowType]::Next)
30}
#追記
上記スクリプトを少し変更し、一番手前の Excel のウィンドウが最前面に出ることを確認しました。
ps1
1Add-Type -TypeDefinition @"
2using System;
3using System.Runtime.InteropServices;
4
5public class Platform
6{
7 [DllImport("user32.dll", SetLastError = true)]
8 public static extern IntPtr GetWindow(IntPtr hwnd, GetWindowType uCmd);
9
10 [DllImport("user32.dll", SetLastError = true)]
11 public static extern IntPtr GetDesktopWindow();
12
13 [DllImport("kernel32.dll")]
14 public static extern uint GetLastError();
15
16 [DllImport("user32.dll")]
17 [return: MarshalAs(UnmanagedType.Bool)]
18 public static extern bool SetForegroundWindow(IntPtr hwnd);
19}
20
21public enum GetWindowType : uint
22{
23 First = 0,
24 Last = 1,
25 Next = 2,
26 Prev = 3,
27 Owner = 4,
28 Child = 5,
29 EnabledPopup = 6
30}
31"@
32function EnumerateWindows
33{
34 $window = [Platform]::GetWindow([Platform]::GetDesktopWindow(), [GetWindowType]::Child)
35 while ($window -ne [IntPtr]::Zero)
36 {
37 $window
38 $window = [Platform]::GetWindow($window, [GetWindowType]::Next)
39 }
40}
41$handles = @(Get-Process | Where-Object { $_.Name -eq 'Excel' } | Foreach-Object { $_.MainWindowHandle })
42if ($handles -eq $null) {
43 return
44}
45$handle = EnumerateWindows | Where-Object { $handles.Contains($_) } | Select-Object -First 1
46[Platform]::SetForegroundWindow($handle)
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/19 10:08
2018/10/19 14:17