Debian Codegraph @

deps/winpty/misc/IdentifyConsoleWindow.ps1

raw
1 #
2 # Usage: powershell <path>\IdentifyConsoleWindow.ps1
3 #
4 # This script determines whether the process has a console attached, whether
5 # that console has a non-NULL window (e.g. HWND), and whether the window is on
6 # the current window station.
7 #
8
9 $signature = @'
10 [DllImport("kernel32.dll", SetLastError=true)]
11 public static extern IntPtr GetConsoleWindow();
12
13 [DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
14 public static extern bool SetConsoleTitle(String title);
15
16 [DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)]
17 public static extern int GetWindowText(IntPtr hWnd,
18 System.Text.StringBuilder lpString,
19 int nMaxCount);
20 '@
21
22 $WinAPI = Add-Type -MemberDefinition $signature `
23 -Name WinAPI -Namespace IdentifyConsoleWindow -PassThru
24
25 if (!$WinAPI::SetConsoleTitle("ConsoleWindowScript")) {
26 echo "error: could not change console title -- is a console attached?"
27 exit 1
28 } else {
29 echo "note: successfully set console title to ""ConsoleWindowScript""."
30 }
31
32 $hwnd = $WinAPI::GetConsoleWindow()
33 if ($hwnd -eq 0) {
34 echo "note: GetConsoleWindow returned NULL."
35 } else {
36 echo "note: GetConsoleWindow returned 0x$($hwnd.ToString("X"))."
37 $sb = New-Object System.Text.StringBuilder -ArgumentList 4096
38 if ($WinAPI::GetWindowText($hwnd, $sb, $sb.Capacity)) {
39 $title = $sb.ToString()
40 echo "note: GetWindowText returned ""${title}""."
41 if ($title -eq "ConsoleWindowScript") {
42 echo "success!"
43 } else {
44 echo "error: expected to see ""ConsoleWindowScript""."
45 echo " (Perhaps the console window is on a different window station?)"
46 }
47 } else {
48 echo "error: GetWindowText could not read the window title."
49 echo " (Perhaps the console window is on a different window station?)"
50 }
51 }