我如何在 powershell 中使用 GetWindowText API 函数?

How i can use GetWindowText API function in powershell?

如何在 powershell 中使用 GetWindowText API 函数?

我这样试过:

    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);
}
"@

我像这样制作字符串生成器:

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

我使用的函数如下:

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

但我收到错误:

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'."

有人可以帮助我使用这个功能吗?如果可以请w写代码。 tnx.

大致是这样的:

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())"
    }

}

您没有在您的代码中说明 $ImportDll 来自何处,但您需要在您定义的 class 上将它们作为静态方法调用。

我的 close-vote 中的 link 中有更完整的示例。


帮助链接(如果可用):

您可以使用 C# 代码声明 class 并在其中编写您的函数,然后在您的程序中使用它。

    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)