回答編集履歴

1

追記

2018/10/19 10:49

投稿

Zuishin
Zuishin

スコア28662

test CHANGED
@@ -65,3 +65,109 @@
65
65
  }
66
66
 
67
67
  ```
68
+
69
+
70
+
71
+ #追記
72
+
73
+
74
+
75
+ 上記スクリプトを少し変更し、一番手前の Excel のウィンドウが最前面に出ることを確認しました。
76
+
77
+
78
+
79
+ ```ps1
80
+
81
+ Add-Type -TypeDefinition @"
82
+
83
+ using System;
84
+
85
+ using System.Runtime.InteropServices;
86
+
87
+
88
+
89
+ public class Platform
90
+
91
+ {
92
+
93
+ [DllImport("user32.dll", SetLastError = true)]
94
+
95
+ public static extern IntPtr GetWindow(IntPtr hwnd, GetWindowType uCmd);
96
+
97
+
98
+
99
+ [DllImport("user32.dll", SetLastError = true)]
100
+
101
+ public static extern IntPtr GetDesktopWindow();
102
+
103
+
104
+
105
+ [DllImport("kernel32.dll")]
106
+
107
+ public static extern uint GetLastError();
108
+
109
+
110
+
111
+ [DllImport("user32.dll")]
112
+
113
+ [return: MarshalAs(UnmanagedType.Bool)]
114
+
115
+ public static extern bool SetForegroundWindow(IntPtr hwnd);
116
+
117
+ }
118
+
119
+
120
+
121
+ public enum GetWindowType : uint
122
+
123
+ {
124
+
125
+ First = 0,
126
+
127
+ Last = 1,
128
+
129
+ Next = 2,
130
+
131
+ Prev = 3,
132
+
133
+ Owner = 4,
134
+
135
+ Child = 5,
136
+
137
+ EnabledPopup = 6
138
+
139
+ }
140
+
141
+ "@
142
+
143
+ function EnumerateWindows
144
+
145
+ {
146
+
147
+ $window = [Platform]::GetWindow([Platform]::GetDesktopWindow(), [GetWindowType]::Child)
148
+
149
+ while ($window -ne [IntPtr]::Zero)
150
+
151
+ {
152
+
153
+ $window
154
+
155
+ $window = [Platform]::GetWindow($window, [GetWindowType]::Next)
156
+
157
+ }
158
+
159
+ }
160
+
161
+ $handles = @(Get-Process | Where-Object { $_.Name -eq 'Excel' } | Foreach-Object { $_.MainWindowHandle })
162
+
163
+ if ($handles -eq $null) {
164
+
165
+ return
166
+
167
+ }
168
+
169
+ $handle = EnumerateWindows | Where-Object { $handles.Contains($_) } | Select-Object -First 1
170
+
171
+ [Platform]::SetForegroundWindow($handle)
172
+
173
+ ```