-
Notifications
You must be signed in to change notification settings - Fork 0
/
saveRSProcesses.ps1
82 lines (64 loc) · 2.53 KB
/
saveRSProcesses.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
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
[DllImport("user32.dll")]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll")]
public static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
public const int SW_RESTORE = 9;
public const int SW_MINIMIZE = 6;
public const byte VK_CONTROL = 0x11;
public const byte VK_S = 0x53;
public const uint KEYEVENTF_KEYUP = 0x0002;
}
"@
function Save-WindowByPID {
param (
[int]$ProcessId
)
$process = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue
if ($process -eq $null) {
Write-Error "No process found with PID $pid"
return
}
$hwnd = $process.MainWindowHandle
if ($hwnd -eq [IntPtr]::Zero) {
Write-Error "The process does not have a main window handle"
return
}
# Minimize the window
[Win32]::ShowWindow($hwnd, [Win32]::SW_MINIMIZE)
# Restore the window
Start-Sleep -Milliseconds 500
[Win32]::ShowWindow($hwnd, [Win32]::SW_RESTORE)
<# # Get the thread IDs
$currentThreadId = [Win32]::GetCurrentThreadId()
[Win32]::GetWindowThreadProcessId($hwnd, [ref]$targetThreadId) | Out-Null
# Attach input threads
[Win32]::AttachThreadInput($currentThreadId, $targetThreadId, $true)
#>
# Set foreground window
[Win32]::SetForegroundWindow($hwnd)
# Detach input threads
[Win32]::AttachThreadInput($currentThreadId, $targetThreadId, $false)
# Wait a bit to ensure the window is focused
Start-Sleep -Milliseconds 1500 # adjust if save not working! (maybe fix in the future)
# Send Ctrl+S
[Win32]::keybd_event([Win32]::VK_CONTROL, 0, 0, 0)
[Win32]::keybd_event([Win32]::VK_S, 0, 0, 0)
[Win32]::keybd_event([Win32]::VK_S, 0, [Win32]::KEYEVENTF_KEYUP, 0)
[Win32]::keybd_event([Win32]::VK_CONTROL, 0, [Win32]::KEYEVENTF_KEYUP, 0)
}
# Call the function
Save-WindowByPID $args[0]