Compare commits

...

3 Commits

Author SHA1 Message Date
Mike Griese
211f3160a5 Or, in powershell 2023-04-14 11:13:38 -05:00
Mike Griese
8db8bd3ec3 Cleanup to help with #13388 2023-04-14 10:51:26 -05:00
Mike Griese
a43ea2b13b I guess the bot wins this round, sorry 2023-04-14 10:44:32 -05:00
2 changed files with 112 additions and 0 deletions

View File

@@ -0,0 +1,55 @@
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
}
"@
function Get-ForegroundWindow {
[System.IntPtr]$handle = [Win32]::GetForegroundWindow()
return $handle
}
function Get-ProcessFromWindowHandle {
param(
[System.IntPtr]$hwnd
)
$p = 0
[Win32]::GetWindowThreadProcessId($hwnd, [ref]$p)
if ($p -ne 0) {
$process = Get-Process -Id $p -ErrorAction SilentlyContinue
if ($process) {
return $process
}
}
return $null
}
$processId = (Get-Process -Id $pid).Id
$processName = (Get-Process -Id $pid).ProcessName
Write-Host "Current process: $processName"
$hwnd = 0;
while ($true) {
$hwndNew = Get-ForegroundWindow;
if ($hwndNew -ne $hwnd) {
$hwnd = $hwndNew
$processIdNew = (Get-ProcessFromWindowHandle $hwnd).Id
if ($processIdNew -ne $processId) {
$processId = $processIdNew
$processName = (Get-Process -Id $processId -FileVersionInfo).FileName
Write-Host "Current process: $processName"
}
}
Start-Sleep -Milliseconds 100
}

View File

@@ -2,9 +2,66 @@
// Licensed under the MIT license.
#include <windows.h>
#include <iostream>
#include <string>
#include <psapi.h>
// This wmain exists for help in writing scratch programs while debugging.
int __cdecl wmain(int /*argc*/, WCHAR* /*argv[]*/)
{
HWND hwnd = GetForegroundWindow();
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
if (hProcess == NULL)
{
std::cerr << "Failed to open process." << std::endl;
return 1;
}
wchar_t processName[MAX_PATH];
if (GetModuleFileNameExW(hProcess, NULL, processName, MAX_PATH) == 0)
{
std::cerr << "Failed to get module file name." << std::endl;
CloseHandle(hProcess);
return 1;
}
wprintf(L"Current process: %s\n", processName);
while (true)
{
HWND hwndNew = GetForegroundWindow();
if (hwndNew != hwnd)
{
hwnd = hwndNew;
DWORD pidNew;
GetWindowThreadProcessId(hwnd, &pidNew);
if (pidNew != pid)
{
pid = pidNew;
CloseHandle(hProcess);
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
if (hProcess == NULL)
{
std::cerr << "Failed to open process." << std::endl;
return 1;
}
if (GetModuleFileNameExW(hProcess, NULL, processName, MAX_PATH) == 0)
{
std::cerr << "Failed to get module file name." << std::endl;
CloseHandle(hProcess);
return 1;
}
wprintf(L"Current process: %s\n", processName);
}
}
Sleep(100);
}
CloseHandle(hProcess);
return 0;
}