Certainly! Below is a PowerShell script that creates a Windows GUI application. This application allows you to select a visible window and then shows mouse click and key press events occurring in that window.
Please note: Capturing input events from other windows may require administrative privileges. Additionally, capturing keyboard and mouse events in other processes involves setting up system-wide hooks, which can be complex and may have security implications. Use this script carefully and understand the code before running it.
powershell
# Load necessary assemblies
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Import necessary Win32 API functions and structures
$win32Code = @"
using System;
using System.Runtime.InteropServices;
using System.Text;
public class Win32 {
// Delegate for the hook callback
public delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);
// Hook types
public const int WH_KEYBOARD_LL = 13;
public const int WH_MOUSE_LL = 14;
// Windows message types
public const int WM_KEYDOWN = 0x0100;
public const int WM_KEYUP = 0x0101;
public const int WM_LBUTTONDOWN = 0x0201;
public const int WM_RBUTTONDOWN = 0x0204;
// Hook handles
public static IntPtr _keyboardHookID = IntPtr.Zero;
public static IntPtr _mouseHookID = IntPtr.Zero;
// Keyboard hook procedure
public static IntPtr KeyboardProc(int nCode, IntPtr wParam, IntPtr lParam) {
if (nCode >= 0 && (wParam == (IntPtr)WM_KEYDOWN)) {
int vkCode = Marshal.ReadInt32(lParam);
string keyName = Enum.GetName(typeof(System.Windows.Forms.Keys), vkCode);
EventHandler.OnKeyPress(keyName);
}
return CallNextHookEx(_keyboardHookID, nCode, wParam, lParam);
}
// Mouse hook procedure
public static IntPtr MouseProc(int nCode, IntPtr wParam, IntPtr lParam) {
if (nCode >= 0 && (wParam == (IntPtr)WM_LBUTTONDOWN || wParam == (IntPtr)WM_RBUTTONDOWN)) {
string button = wParam == (IntPtr)WM_LBUTTONDOWN ? "Left" : "Right";
EventHandler.OnMouseClick(button);
}
return CallNextHookEx(_mouseHookID, nCode, wParam, lParam);
}
// Set hooks
public static void SetHooks() {
_keyboardHookID = SetHook(WH_KEYBOARD_LL, KeyboardProc);
_mouseHookID = SetHook(WH_MOUSE_LL, MouseProc);
}
// Remove hooks
public static void RemoveHooks() {
UnhookWindowsHookEx(_keyboardHookID);
UnhookWindowsHookEx(_mouseHookID);
}
// Helper to set a hook
private static IntPtr SetHook(int idHook, HookProc proc) {
using (System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess())
using (System.Diagnostics.ProcessModule curModule = curProcess.MainModule) {
return SetWindowsHookEx(idHook, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
// Win32 API functions
[DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
// Declarations for window enumeration
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")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxCount);
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hWnd);
// Function to get window title
public static string GetWindowTitle(IntPtr hWnd) {
StringBuilder sb = new StringBuilder(256);
GetWindowText(hWnd, sb, sb.Capacity);
return sb.ToString();
}
}
// Event handler class to relay events to PowerShell
public class EventHandler {
public static void OnKeyPress(string key) {
// Write to console to capture in PowerShell
Console.WriteLine("Key Pressed: " + key);
}
public static void OnMouseClick(string button) {
Console.WriteLine(button + " Mouse Button Clicked");
}
}
"@
Add-Type -TypeDefinition $win32Code -Language CSharpVersion3
# Define a function to enumerate all visible windows
function Get-VisibleWindows {
$windows = @{}
$callback = [Win32+EnumWindowsProc]{
param([IntPtr]$hWnd, [IntPtr]$lParam)
if ([Win32]::IsWindowVisible($hWnd)) {
$title = [Win32]::GetWindowTitle($hWnd)
if (![string]::IsNullOrEmpty($title)) {
$windows[$hWnd] = $title
}
}
return $true
}
[Win32]::EnumWindows($callback, [IntPtr]::Zero) | Out-Null
return $windows
}
# Create the main form
$form = New-Object System.Windows.Forms.Form
$form.Text = "Windows Event Monitor"
$form.Size = New-Object System.Drawing.Size(600, 400)
$form.StartPosition = "CenterScreen"
# Create and populate the window list box
$windowList = New-Object System.Windows.Forms.ListBox
$windowList.Location = New-Object System.Drawing.Point(10, 10)
$windowList.Size = New-Object System.Drawing.Size(250, 300)
$windowList.SelectionMode = "One"
$form.Controls.Add($windowList)
$windows = Get-VisibleWindows
foreach ($entry in $windows.GetEnumerator()) {
$item = New-Object System.Windows.Forms.ListBox+ObjectCollection $windowList, "{0} - {1}" -f $entry.Key, $entry.Value
$windowList.Items.Add($item)
}
# Create a text box to display the events
$logBox = New-Object System.Windows.Forms.TextBox
$logBox.Location = New-Object System.Drawing.Point(270, 10)
$logBox.Size = New-Object System.Drawing.Size(300, 300)
$logBox.Multiline = $true
$logBox.ScrollBars = "Vertical"
$logBox.ReadOnly = $true
$form.Controls.Add($logBox)
# Create Start and Stop buttons
$startButton = New-Object System.Windows.Forms.Button
$startButton.Text = "Start Monitoring"
$startButton.Location = New-Object System.Drawing.Point(10, 320)
$startButton.Enabled = $false
$form.Controls.Add($startButton)
$stopButton = New-Object System.Windows.Forms.Button
$stopButton.Text = "Stop Monitoring"
$stopButton.Location = New-Object System.Drawing.Point(120, 320)
$stopButton.Enabled = $false
$form.Controls.Add($stopButton)
$selectedWindowHandle = [IntPtr]::Zero
$globalTimer = $null
# Update the Start button when a window is selected
$windowList.SelectedIndexChanged += {
if ($windowList.SelectedIndex -ge 0) {
$startButton.Enabled = $true
} else {
$startButton.Enabled = $false
}
}
# Start monitoring events
$startButton.Add_Click({
$selectedItem = $windowList.SelectedItem
if ($selectedItem -match "^([0-9]+) -") {
$selectedWindowHandle = [IntPtr][int64]$matches[1]
$logBox.AppendText("Monitoring started on window: $selectedItem`r`n")
$startButton.Enabled = $false
$stopButton.Enabled = $true
# Set up the hooks
[Win32]::SetHooks()
# Set up a timer to read the console output
$globalTimer = [System.Timers.Timer]::new(100)
$globalTimer.AutoReset = $true
$globalTimer.Enabled = $true
$globalTimer.Add_Elapsed({
$line = $Host.UI.RawUI.ReadBufferLine(0)
if ($line -and $line.Length -gt 0) {
$logBox.Invoke([Action]{ $logBox.AppendText($line + "`r`n") })
$Host.UI.RawUI.CursorPosition = [System.Management.Automation.Host.Coordinates]::new(0,0)
$Host.UI.RawUI.BufferSize = [System.Management.Automation.Host.Size]::new($Host.UI.RawUI.BufferSize.Width, 1)
}
})
}
})
# Stop monitoring events
$stopButton.Add_Click({
[Win32]::RemoveHooks()
if ($globalTimer) {
$globalTimer.Stop()
$globalTimer.Dispose()
$globalTimer = $null
}
$logBox.AppendText("Monitoring stopped.`r`n")
$startButton.Enabled = $true
$stopButton.Enabled = $false
})
# Run the form
[System.Windows.Forms.Application]::EnableVisualStyles()
[System.Windows.Forms.Application]::Run($form)
Explanation:
Assemblies: The script loads necessary assemblies for Windows Forms and Drawing.
Win32 APIs: It defines C# code within the PowerShell script using Add-Type to import necessary Win32 API functions for setting hooks and enumerating windows.
Window Enumeration: The Get-VisibleWindows function uses EnumWindows to list all visible windows and their handles.
GUI Setup: The script creates a Windows Form with:
A ListBox to display the list of visible windows.
A TextBox (logBox) to display captured events.
Start and Stop buttons to control monitoring.
Event Handling:
When the user selects a window from the list and clicks Start Monitoring, the script sets up global low-level keyboard and mouse hooks using the SetWindowsHookEx function.
The hooks capture all keyboard and mouse events and invoke the respective callback functions (KeyboardProc and MouseProc) defined in the C# code.
These callback functions write events to the console, which the PowerShell script reads and displays in the logBox.
Timer: A System.Timers.Timer is used to periodically check the console output and update the logBox with new events.
Start/Stop Monitoring:
The Start Monitoring button initializes hooks and starts the timer to read events.
The Stop Monitoring button removes hooks and stops the timer.
Important Notes:
Global Hooks: The script sets up global hooks, meaning it captures events system-wide, not just for the selected window. Filtering events for a specific window requires more complex logic and may not be fully achievable with low-level hooks in user-space code.
Permissions: Setting global hooks often requires administrative privileges. Run PowerShell as Administrator to ensure the script works correctly.
Performance: Using global hooks can impact system performance. Use this script cautiously and avoid leaving it running longer than necessary.
Security: Capturing input from other processes can have security implications. Ensure you have permission to monitor the target applications and understand the legal considerations in your environment.
Disclaimer: Be cautious when running scripts that utilize system hooks, as they can interfere with system behavior and security. Make sure you understand the code and test it in a safe environment.
I hope this script helps you monitor clicks and key press events on the selected window. If you have any questions or need further assistance, feel free to ask!