1

I have a script that is invoked via right click context menu in Windows Explorer. I'm not sure if this is possible, but I want to capture the HWND of the window from which I invoked the script. Right now I have this:

Add-Type @"
    using System;
    using System.Runtime.InteropServices;
    public class Util {
      [DllImport("user32.dll")]
      [return: MarshalAs(UnmanagedType.Bool)]
      public static extern bool SetForegroundWindow(IntPtr hWnd);

      [DllImport("user32.dll")]
      [return: MarshalAs(UnmanagedType.Bool)]
      public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

      [DllImport("user32.dll")]
      public static extern IntPtr GetForegroundWindow();
    }
"@

$hwnd = [Util]::GetForegroundWindow()
Start-Sleep -Milliseconds 300
[void] [Util]::SetForegroundWindow($hwnd)

But it doesn't work because $hwnd gets assigned to the interactive console window when the script launches. I know I could probably hide the console using some kind of helper tool and that might work. But I'm wondering if there is a clean way or some kind of buried method to capture the correct explorer window.

Hopefully this makes sense. Any help appreciated.

mklement0
  • 382,024
  • 64
  • 607
  • 775
fmotion1
  • 237
  • 4
  • 12
  • 1
    See if [this answer](https://stackoverflow.com/a/57136189/45375) helps, If so, we can close your question as a duplicate. – mklement0 Aug 09 '22 at 18:16
  • 1
    That link went above and beyond what I expected, thank you so much. Feel free to close this as a duplicate. – fmotion1 Aug 09 '22 at 18:24

0 Answers0