write code for a powershell gui app for selecting visivle window and its clicks and…
- User
write code for a powershell gui app for selecting visivle window and its clicks and keypress events
- Assistant
write code for a powershell gui app for selecting visivle window and its clicks and keypress events
Creating a PowerShell GUI application that allows users to select a visible window and monitor its mouse click and keypress events involves several steps. Due to the complexity of interacting with Windows APIs for hooking into window events, we'll leverage both PowerShell and embedded C# code to accomplish this task.
Below is a comprehensive PowerShell script that:
Execution Policy: Ensure that your PowerShell execution policy allows running scripts. You can set it using:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Administrator Privileges: Running global hooks often requires administrative rights. It's recommended to run the PowerShell script as an administrator.
Add-Type @"
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class WindowHelper
{
// Delegate and imports for enumerating windows
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
public static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hWnd);
}
public class MouseKeyboardHook
{
// Constants for mouse hooks
private const int WH_MOUSE_LL = 14;
private const int WH_KEYBOARD_LL = 13;
// Mouse event constants
public const int WM_LBUTTONDOWN = 0x0201;
public const int WM_RBUTTONDOWN = 0x0204;
// Keyboard event constants
public const int WM_KEYDOWN = 0x0100;
private static LowLevelMouseProc _mouseProc = MouseHookCallback;
private static LowLevelKeyboardProc _keyboardProc = KeyboardHookCallback;
private static IntPtr _mouseHookID = IntPtr.Zero;
private static IntPtr _keyboardHookID = IntPtr.Zero;
public delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
public static event Action<string> OnMouseEvent;
public static event Action<string> OnKeyboardEvent;
[DllImport("user32.dll", SetLastError=true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", SetLastError=true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", SetLastError=true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
public static void SetHooks()
{
_mouseHookID = SetWindowsHookEx(WH_MOUSE_LL, _mouseProc, GetModuleHandle(null), 0);
_keyboardHookID = SetWindowsHookEx(WH_KEYBOARD_LL, _keyboardProc, GetModuleHandle(null), 0);
}
public static void RemoveHooks()
{
UnhookWindowsHookEx(_mouseHookID);
UnhookWindowsHookEx(_keyboardHookID);
}
private static IntPtr MouseHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
{
if (wParam == (IntPtr)WM_LBUTTONDOWN)
{
OnMouseEvent?.Invoke("Left Button Clicked");
}
else if (wParam == (IntPtr)WM_RBUTTONDOWN)
{
OnMouseEvent?.Invoke("Right Button Clicked");
}
}
return CallNextHookEx(_mouseHookID, nCode, wParam, lParam);
}
private static IntPtr KeyboardHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
{
if (wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
string key = ((Keys)vkCode).ToString();
OnKeyboardEvent?.Invoke($"Key Pressed: {key}");
}
}
return CallNextHookEx(_keyboardHookID, nCode, wParam, lParam);
}
}
"@
# Import necessary .NET namespaces
using namespace System
using namespace System.Windows.Forms
using namespace System.Drawing
# Function to retrieve all visible window titles
function Get-VisibleWindows {
$windows = @()
[WindowHelper]::EnumWindows({ param($hWnd, $lParam)
if ([WindowHelper]::IsWindowVisible($hWnd)) {
$sb = New-Object System.Text.StringBuilder 256
[WindowHelper]::GetWindowText($hWnd, $sb, $sb.Capacity) | Out-Null
$title = $sb.ToString()
if (![string]::IsNullOrWhiteSpace($title)) {
$windows += New-Object PSObject -Property @{
Handle = $hWnd
Title = $title
}
}
}
return $true
}, [IntPtr]::Zero)
return $windows
}
# Create the main form
$form = New-Object Windows.Forms.Form
$form.Text = "Window Event Monitor"
$form.Size = New-Object Drawing.Size(600,400)
$form.StartPosition = "CenterScreen"
# Create a combo box to list windows
$comboBox = New-Object Windows.Forms.ComboBox
$comboBox.Location = New-Object Drawing.Point(20,20)
$comboBox.Size = New-Object Drawing.Size(540,25)
$form.Controls.Add($comboBox)
# Populate the combo box with visible windows
$windows = Get-VisibleWindows
foreach ($win in $windows) {
$comboBox.Items.Add("$($win.Title) (Handle: 0x$($win.Handle.ToInt64().ToString("X")))")
}
if ($comboBox.Items.Count -gt 0) {
$comboBox.SelectedIndex = 0
}
# Create a button to start monitoring
$startButton = New-Object Windows.Forms.Button
$startButton.Text = "Start Monitoring"
$startButton.Location = New-Object Drawing.Point(20,60)
$startButton.Size = New-Object Drawing.Size(150,30)
$form.Controls.Add($startButton)
# Create a button to stop monitoring
$stopButton = New-Object Windows.Forms.Button
$stopButton.Text = "Stop Monitoring"
$stopButton.Location = New-Object Drawing.Point(180,60)
$stopButton.Size = New-Object Drawing.Size(150,30)
$stopButton.Enabled = $false
$form.Controls.Add($stopButton)
# Create a multiline textbox to display logs
$logBox = New-Object Windows.Forms.TextBox
$logBox.Location = New-Object Drawing.Point(20,110)
$logBox.Size = New-Object Drawing.Size(540,240)
$logBox.Multiline = $true
$logBox.ScrollBars = 'Vertical'
$logBox.ReadOnly = $true
$form.Controls.Add($logBox)
# Variable to store monitoring state
$monitoring = $false
# Event Handlers
$startButton.Add_Click({
if (-not $monitoring) {
if ($comboBox.SelectedIndex -ge 0) {
# Here, you can implement logic to bind hooks to the selected window
# However, global hooks are not window-specific.
# For demonstration, we'll set up global hooks.
try {
[MouseKeyboardHook]::OnMouseEvent += {
param($msg)
$logBox.AppendText("[Mouse] $msg`n")
}
[MouseKeyboardHook]::OnKeyboardEvent += {
param($msg)
$logBox.AppendText("[Keyboard] $msg`n")
}
[MouseKeyboardHook]::SetHooks()
$monitoring = $true
$startButton.Enabled = $false
$stopButton.Enabled = $true
$logBox.AppendText("Monitoring started on window: $($comboBox.SelectedItem)`n")
}
catch {
[System.Windows.Forms.MessageBox]::Show("Failed to set hooks. Run as Administrator.", "Error", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Error)
}
}
else {
[System.Windows.Forms.MessageBox]::Show("Please select a window to monitor.", "Info", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information)
}
}
})
$stopButton.Add_Click({
if ($monitoring) {
[MouseKeyboardHook]::RemoveHooks()
[MouseKeyboardHook]::OnMouseEvent = $null
[MouseKeyboardHook]::OnKeyboardEvent = $null
$monitoring = $false
$startButton.Enabled = $true
$stopButton.Enabled = $false
$logBox.AppendText("Monitoring stopped.`n")
}
})
# Refresh button to update window list
$refreshButton = New-Object Windows.Forms.Button
$refreshButton.Text = "Refresh Window List"
$refreshButton.Location = New-Object Drawing.Point(340,60)
$refreshButton.Size = New-Object Drawing.Size(150,30)
$form.Controls.Add($refreshButton)
$refreshButton.Add_Click({
$comboBox.Items.Clear()
$windows = Get-VisibleWindows
foreach ($win in $windows) {
$comboBox.Items.Add("$($win.Title) (Handle: 0x$($win.Handle.ToInt64().ToString("X")))")
}
if ($comboBox.Items.Count -gt 0) {
$comboBox.SelectedIndex = 0
}
else {
[System.Windows.Forms.MessageBox]::Show("No visible windows found.", "Info", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Information)
}
})
# Handle form closing to ensure hooks are removed
$form.Add_FormClosing({
if ($monitoring) {
[MouseKeyboardHook]::RemoveHooks()
}
})
# Run the form
[void] $form.ShowDialog()
Importing C# Code Using Add-Type:
WindowHelper Class: Utilizes Windows API functions to enumerate all visible windows and retrieve their titles.
MouseKeyboardHook Class: Sets up low-level mouse and keyboard hooks using the SetWindowsHookEx API. It listens for mouse clicks (WM_LBUTTONDOWN, WM_RBUTTONDOWN) and keypresses (WM_KEYDOWN). When such events are detected, corresponding actions are invoked to handle these events.
Retrieving Visible Windows:
Get-VisibleWindows function uses the WindowHelper class to enumerate all visible windows and collect their handles and titles. This list populates the combo box in the GUI.Creating the GUI:
Form: A Windows Form titled "Window Event Monitor" with a size of 600x400 pixels.
ComboBox: Lists all visible windows for selection.
Buttons:
TextBox (logBox): A multiline, read-only textbox that logs all captured mouse and keyboard events.
Event Handling:
Start Button:
OnMouseEvent and OnKeyboardEvent events to log activities in real-time.Stop Button:
Refresh Button:
Form Closing:
Global Hooks: The provided hooks (WH_MOUSE_LL and WH_KEYBOARD_LL) are low-level global hooks. This means they monitor events system-wide, not just for the selected window. Filtering events for a specific window involves determining the active window at the time of the event or modifying the hooking mechanism to target a specific window/thread, which can be more complex and is beyond the scope of this script.
Performance Impact: Global hooks can impact system performance if not managed correctly. Ensure that hooks are removed appropriately to prevent resource leaks.
Security: Running scripts that set global hooks may require administrative privileges. Always ensure scripts are obtained from trusted sources to prevent security risks.
Save the Script: Copy the above script into a .ps1 file, e.g., WindowEventMonitor.ps1.
Run as Administrator: Right-click on PowerShell and select "Run as Administrator".
Execute the Script:
.\WindowEventMonitor.ps1
Using the Application:
Filtering Events for Specific Window: To monitor events exclusively for a selected window, additional logic is required to check the window handle (hWnd) corresponding to each event. This may involve more advanced Windows API functions to map events to specific windows.
Visual Indicators: Enhance the GUI by adding indicators (like changing colors) when specific events occur.
Logging to File: Extend functionality to log events to a file for later analysis.
Exception Handling: Improve robustness by adding more comprehensive error handling mechanisms.
The above PowerShell script provides a foundational GUI application to monitor mouse and keyboard events. While it sets up global hooks due to the limitations of directly targeting a specific window with hooks in PowerShell, it serves as a starting point. For more advanced and window-specific monitoring, consider developing the application in C# or another language with more direct access to Windows APIs and better support for threading and event handling.
Not yet included in a published release.