Is there a way to get access to a window handle in windows using WSH, or WMI or similar?

15,336

Solution 1

To grab it with WSH, you can use the COM DLL found in this CodeProject article. Using this, you can then grab a window handle like so:

Set obj = CreateObject("APIWrapperCOM.APIWrapper")
winHandle = obj.FindWindow("test.txt - Notepad")

This is also very easy in PowerShell.

example:

(Get-Process powershell).MainWindowHandle

This grab's the window handle of the PowerShell process.


Although if your main goal is to make a window topmost, there are many programs for this such as DeskPins:

alt text

Solution 2

I know it's a massive necro and pardon if it was solved already, but I've been struggling with it for some time now and here's a really simple solution I wrote:

function WinExist($winTitle, $instance = 0)
{
    $h = Get-Process | Where-Object { $_.MainWindowTitle -match $winTitle } | ForEach-Object { $_.MainWindowHandle }
    if ( $h -eq $null )
    {
        return 0
    }
    else
    {
        if ( $h -is [System.Array] )
        {

            $h = $h[$instance]
        }
        return $h
    }
}

Returns "0" if window wasn't found, or the window handle. If found more windows matching the $winTitle string it returns the $instance number (0 means first window, 1 second, etc.).

Example:

# WinExist str_WindowTitle int_WindowNumber
# returns the handle of second notepad window (if more than 1 opened)
$hwnd = WinExist "notepad" 1 
Share:
15,336

Related videos on Youtube

Nathan Runge
Author by

Nathan Runge

Updated on September 17, 2022

Comments

  • Nathan Runge
    Nathan Runge almost 2 years

    Is there a way to get access to a window handle in windows using WSH, or WMI or similar? I just want to flag a window as always-on-top. Ideally I'd use windows script host for this.

    (Should also be tagged as WSH).

    Regards,

    • John T
      John T over 14 years
      added WSH tag for ya
  • Nathan Runge
    Nathan Runge over 14 years
    Thanks John, but I'm ideally after a .VBS solution. We're a bit nervous about what we run on this particular machine and have other VBS files running as part of the system.
  • John T
    John T over 14 years
    Ah well, I tried. Thought this might fall into the "or similar" category :P
  • John T
    John T over 14 years
    added a WSH solution :)
  • Metallkiller
    Metallkiller over 6 years
    Can I also get the window handle of the current powershell window? Since I have 3 windows open, I get three handles. I could just try each one and see which is the one I want, but that can't be automated.
  • MarredCheese
    MarredCheese almost 3 years
    @Metallkiller (Get-Process -id $pid).MainWindowHandle does that since $pid "contains the process identifier (PID) of the process that is hosting the current PowerShell session."