question

MarkFratto-7237 avatar image
0 Votes"
MarkFratto-7237 asked MarkFratto-7237 answered

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

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
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

You really haven't described a "listener". You've created a loop that gets the window that's in the foreground at the time the loop runs.

You'd have to "hook" an event to have a listener! That can present a problem because, IIRC, you can't hook global events from managed code. That gets you to the need for either C or C++.

Maybe something like this: 20131202-00
or: detect-active-window-changed-using-c-sharp-without-polling


0 Votes 0 ·
LimitlessTechnology-2700 avatar image
0 Votes"
LimitlessTechnology-2700 answered

Hi @MarkFratto-7237

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://docs.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--

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

MarkFratto-7237 avatar image
0 Votes"
MarkFratto-7237 answered

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

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.