Creating a PowerShell GUI application that monitors click and key press events for a selected visible window involves several steps, including interacting with Windows APIs to enumerate windows, set hooks for input events, and update the GUI accordingly. PowerShell alone isn't ideally suited for setting low-level hooks, but by leveraging embedded C# code within PowerShell, we can achieve the desired functionality.
Below is a comprehensive PowerShell script that accomplishes this:
Enumerate Visible Windows: Lists all currently visible windows for the user to select.
Select a Window: Allows the user to select a target window from the list.
Set Up Hooks: Uses embedded C# to set low-level keyboard and mouse hooks.
Filter Events: Captures events related only to the selected window.
Display Events: Updates the GUI with the captured click and key press events.
Full PowerShell Script
powershell
# Ensure the script runs with the necessary privileges
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Warning "You need to run this script as an Administrator."
exit
}
Add-Type -TypeDefinition @"
using System;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class Hook
{
// Delegate and import necessary WinAPI functions
public delegate IntPtr LowLevelProc(int nCode, IntPtr wParam, IntPtr lParam);
public LowLevelProc proc;
public IntPtr hookID = IntPtr.Zero;
// Constants for hook types
public const int WH_KEYBOARD_LL = 13;
public const int WH_MOUSE_LL = 14;
// Events to handle
public event Action<string> OnKeyPressed;
public event Action<string> OnMouseClicked;
// User32 functions
[DllImport("user32.dll", SetLastError=true)]
public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", SetLastError=true)]
public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
// Keyboard hook callback
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
{
const int WM_KEYDOWN = 0x0100;
if (wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
string key = ((Keys)vkCode).ToString();
OnKeyPressed?.Invoke(key);
}
}
return CallNextHookEx(hookID, nCode, wParam, lParam);
}
// Mouse hook callback
private IntPtr MouseHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if(nCode >=0 )
{
const int WM_LBUTTONDOWN = 0x0201;
const int WM_RBUTTONDOWN = 0x0204;
if (wParam == (IntPtr)WM_LBUTTONDOWN)
{
OnMouseClicked?.Invoke("Left Click");
}
else if (wParam == (IntPtr)WM_RBUTTONDOWN)
{
OnMouseClicked?.Invoke("Right Click");
}
}
return CallNextHookEx(hookID, nCode, wParam, lParam);
}
// Method to start keyboard hook
public void StartKeyboardHook()
{
proc = HookCallback;
hookID = SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(null), 0);
if (hookID == IntPtr.Zero)
{
throw new System.ComponentModel.Win32Exception();
}
}
// Method to start mouse hook
public void StartMouseHook()
{
proc = MouseHookCallback;
hookID = SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(null), 0);
if (hookID == IntPtr.Zero)
{
throw new System.ComponentModel.Win32Exception();
}
}
// Method to stop hooks
public void StopHook()
{
UnhookWindowsHookEx(hookID);
}
}
"@
# Load necessary assemblies
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Function to enumerate all visible windows
function Get-VisibleWindows {
Add-Type @"
using System;
using System.Text;
using System.Runtime.InteropServices;
public class WindowEnumerator
{
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", SetLastError=true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hWnd);
public static System.Collections.Generic.List<Tuple<IntPtr, string>> GetOpenWindows()
{
var windows = new System.Collections.Generic.List<Tuple<IntPtr, string>>();
EnumWindows(delegate(IntPtr hWnd, IntPtr lParam) {
if (IsWindowVisible(hWnd)) {
StringBuilder sb = new StringBuilder(1024);
GetWindowText(hWnd, sb, sb.Capacity);
string title = sb.ToString();
if (!string.IsNullOrEmpty(title))
{
windows.Add(new Tuple<IntPtr, string>(hWnd, title));
}
}
return true;
}, IntPtr.Zero);
return windows;
}
}
"@
[WindowEnumerator]::GetOpenWindows()
}
# Create the Windows Form
$form = New-Object System.Windows.Forms.Form
$form.Text = "Window Event Monitor"
$form.Size = New-Object System.Drawing.Size(600,400)
$form.StartPosition = "CenterScreen"
# Dropdown to select window
$comboBox = New-Object System.Windows.Forms.ComboBox
$comboBox.Location = New-Object System.Drawing.Point(10,10)
$comboBox.Size = New-Object System.Drawing.Size(560,20)
$form.Controls.Add($comboBox)
# Button to refresh window list
$refreshButton = New-Object System.Windows.Forms.Button
$refreshButton.Location = New-Object System.Drawing.Point(10,40)
$refreshButton.Size = New-Object System.Drawing.Size(100,23)
$refreshButton.Text = "Refresh Windows"
$form.Controls.Add($refreshButton)
# TextBox to display events
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,70)
$textBox.Size = New-Object System.Drawing.Size(560,280)
$textBox.Multiline = $true
$textBox.ScrollBars = "Vertical"
$form.Controls.Add($textBox)
# Populate the ComboBox with visible windows
function Populate-Windows {
$comboBox.Items.Clear()
$windows = Get-VisibleWindows
foreach ($win in $windows) {
$item = "$($win.Item1)`t$($win.Item2)"
$comboBox.Items.Add($item)
}
if ($comboBox.Items.Count -gt 0) {
$comboBox.SelectedIndex = 0
}
}
Populate-Windows
# Handle Refresh button click
$refreshButton.Add_Click({
Populate-Windows
})
# Initialize Hook objects
$keyboardHook = New-Object Hook
$mouseHook = New-Object Hook
# Variable to hold selected window handle
$global:selectedHwnd = [IntPtr]::Zero
# Function to get process ID from window handle
function Get-ProcessIdFromHwnd($hwnd) {
$proc = Get-Process | Where-Object { $_.MainWindowHandle -eq $hwnd }
return $proc.Id
}
# Event handlers for hooks
$keyboardHook.OnKeyPressed += {
param($key)
# Optionally, you can filter by active window
$activeHwnd = (Get-ForegroundWindow)
if ($activeHwnd -eq $selectedHwnd) {
$time = Get-Date -Format "HH:mm:ss"
$form.Invoke( [Action]{
$textBox.AppendText("[$time] Key Pressed: $key`n")
})
}
}
$mouseHook.OnMouseClicked += {
param($button)
$activeHwnd = (Get-ForegroundWindow)
if ($activeHwnd -eq $selectedHwnd) {
$time = Get-Date -Format "HH:mm:ss"
$form.Invoke( [Action]{
$textBox.AppendText("[$time] Mouse Clicked: $button`n")
})
}
}
# Import necessary functions for foreground window
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WinAPI
{
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
"@
function Get-ForegroundWindow {
return [WinAPI]::GetForegroundWindow()
}
# Handle window selection change
$comboBox.Add_SelectedIndexChanged({
$selectedIndex = $comboBox.SelectedIndex
if ($selectedIndex -ge 0) {
$selectedItem = $comboBox.SelectedItem
$tokens = $selectedItem -split "`t"
$hwndStr = $tokens[0]
$hwnd = [IntPtr]::Parse($hwndStr)
$selectedHwnd = $hwnd
# Optional: Clear previous events
$textBox.Clear()
}
})
# Start hooks when a window is selected
$form.Add_Shown({
# Ensure a window is selected
if ($comboBox.SelectedIndex -ge 0) {
$selectedItem = $comboBox.SelectedItem
$tokens = $selectedItem -split "`t"
$hwndStr = $tokens[0]
$hwnd = [IntPtr]::Parse($hwndStr)
$selectedHwnd = $hwnd
}
# Start the hooks
try {
$keyboardHook.StartKeyboardHook()
$mouseHook.StartMouseHook()
}
catch {
[System.Windows.Forms.MessageBox]::Show("Failed to set hooks. Run as Administrator.","Error",[System.Windows.Forms.MessageBoxButtons]::OK,[System.Windows.Forms.MessageBoxIcon]::Error)
$form.Close()
}
})
# Stop hooks on form closing
$form.Add_FormClosing({
$keyboardHook.StopHook()
$mouseHook.StopHook()
})
# Show the form
[void]$form.ShowDialog()
# C# Helper Class for Window Handle Equality (if needed)
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class WindowHelper
{
[DllImport("user32.dll")]
public static extern bool IsWindow(IntPtr hWnd);
}
"@
Explanation of the Script
Administrator Privileges Check:
The script first checks if it's being run with administrative privileges, which are necessary for setting low-level hooks. If not, it warns the user and exits.
Embedded C# Code for Hooks:
The script uses Add-Type to define a C# class Hook that can set and manage low-level keyboard and mouse hooks using Windows API functions (SetWindowsHookEx, CallNextHookEx, etc.).
The Hook class defines events OnKeyPressed and OnMouseClicked to handle key presses and mouse clicks, respectively.
Enumerating Visible Windows:
A function Get-VisibleWindows is defined using embedded C# to enumerate all visible windows using EnumWindows and filter out those without a title.
GUI Creation with Windows Forms:
A Windows Form is created with:
A ComboBox to list all visible windows.
A Refresh button to refresh the window list.
A multiline TextBox to display captured events.
Populating Window List:
The Populate-Windows function populates the ComboBox with the list of visible windows retrieved by Get-VisibleWindows.
Hook Initialization and Event Handling:
Two hook objects, $keyboardHook and $mouseHook, are instantiated from the Hook class.
Event handlers are assigned to update the TextBox when key presses or mouse clicks are detected only in the selected window's context.
Foreground Window Detection:
The script defines a helper function Get-ForegroundWindow using embedded C# to retrieve the currently active (foreground) window.
Events are logged only if the active window matches the selected window from the ComboBox.
Handling Window Selection and Hook Activation:
When the user selects a different window from the , the script updates the target window handle.
Important Notes
Running as Administrator: Setting low-level hooks often requires administrative privileges. Ensure you run the PowerShell script with elevated permissions.
Performance Considerations: Low-level hooks can impact system performance if not managed properly. This script ensures hooks are removed when the form is closed.
Security Implications: Hooking global input events can be sensitive. Ensure you understand the security implications and use this script responsibly.
Limitations:
The script monitors events only when the selected window is the active window (foreground). Monitoring events in the background window would require more complex handling.
Some applications may have elevated privileges or protections that prevent hooks from capturing their events.
Running the Script
Save the Script:
Save the above script to a .ps1 file, for example, WindowEventMonitor.ps1.
Run PowerShell as Administrator:
Right-click on PowerShell and select "Run as Administrator".
Execute the Script:
Navigate to the script's directory and execute it:
This will open the GUI where you can select a window and start monitoring its key presses and mouse clicks.
Conclusion
While PowerShell isn't inherently designed for creating complex GUI applications or setting low-level hooks, combining it with embedded C# code provides a powerful way to extend its capabilities. The provided script offers a foundation that you can further enhance based on specific requirements, such as filtering specific keys or mouse buttons, logging events to a file, or integrating additional functionalities.