I need to create an event lisener like can be done in JS but for Powershell

Mark Fratto 21 Reputation points
2021-10-09T17:16:55.653+00:00

So bassically now I have a coninutous loop. But what I am trying to do is find a way to create a listener in PS to kick off the script to identify the application each time and only when the active window/application in the forground changes.

Any help would be apreciated

what I have:::

for (($i = 0))
{
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Tricks {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
"@

$a = [tricks]::GetForegroundWindow()

$WH = get-process | ? { $_.mainwindowhandle -eq $a }
echo $WH

Start-Sleep 5
}

and bassically what i want but have no clue as to accomplish this in Powershell. I made it for my chrome extension for active tab changes, now just need to figure it out for windows app changes. If at all possible

eg. listener for when active windows changes
{
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Tricks {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
"@

$a = [tricks]::GetForegroundWindow()

$WH = get-process | ? { $_.mainwindowhandle -eq $a }
echo $WH
}

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,363 questions
{count} votes

Accepted answer
  1. Limitless Technology 39,351 Reputation points
    2021-10-15T18:14:32.783+00:00

    Hi @Mark Fratto

    I came across this and hope this might help you.

    Use Asynchronous Event Handling in PowerShell
    https://devblogs.microsoft.com/scripting/use-asynchronous-event-handling-in-powershell/

    Add a click event handler to each label
    https://learn.microsoft.com/en-us/visualstudio/ide/step-4-add-a-click-event-handler-to-each-label?view=vs-2019

    ----------

    --If the reply is helpful, please Upvote and Accept as answer--

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Mark Fratto 21 Reputation points
    2021-10-16T02:25:19.477+00:00

    This should help get me in the right direction. Thank you both for the input. Much appreciated! and Have a great weekend!!

    0 comments No comments