1

How i can use GetWindowText API function in powershell ?

i tried this way :

    Add-Type @"
  using System;
  using System.Runtime.InteropServices;
  public class UserWindowss {
    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);
}
"@

and i make string builder like this :

$stringbuilder = New-Object System.Text.StringBuilder
$stringbuilder.Capacity =256

i used function like :

$WindowTitless = $ImportDll::GetWindowText($TopWindow, $stringbuilder, 256)

but i got error :

ERROR: test: Failed to get active Window details. More Info: Exception calling "GetWindowText" with "3" argument(s): "Unable to find an entry point named
ERROR: 'GetWindowText' in DLL 'user32.dll'."

some one can give me help to use this function ? if you can please write code . tnx.

saftargholi
  • 896
  • 1
  • 9
  • 25
  • Possible duplicate of [How can I get all window handles by a process in Powershell?](http://stackoverflow.com/questions/25369285/how-can-i-get-all-window-handles-by-a-process-in-powershell) – TessellatingHeckler Nov 01 '16 at 05:50
  • FYI, you can get titles from Get-Process like: Get-Process | where ProcessName -like 'notepad' | Select MainWindowHandle, MainWindowTitle – Kory Gill Nov 01 '16 at 06:23

2 Answers2

7

Roughly this:

Add-Type @"
  using System;
  using System.Runtime.InteropServices;
  public class UserWindows {
    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);
}
"@

$stringbuilder = New-Object System.Text.StringBuilder 256

Get-Process | ForEach-Object {

    $count = [UserWindows]::GetWindowText($_.MainWindowHandle, $stringbuilder, 256)

    if (0 -lt $count) {
        "$($_.ProcessName) $($stringbuilder.ToString())"
    }

}

You didn't say where $ImportDll came from in your code, but you need to be calling them as static methods on the class you defined.

The link in my close-vote has more complete examples in it.


Help Links (if available):

TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
0

You can declare class with c# code and write your function in it then use it in your program .

    Add-Type @"
  using System;
  using System.Runtime.InteropServices;
  public class UserWindowss {
    [DllImport("user32.dll")]
    public static extern IntPtr GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);
}
"@
[UserWindowss]::GetWindowText(hwnd , stringbuilder , count)