【问题标题】:Powershell and WinApi EnumWindows functionPowershell 和 WinApi EnumWindows 函数
【发布时间】:2020-10-21 18:36:57
【问题描述】:
$f=@'
[DllImport("user32.dll")]
private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
);
'@
$winList = Add-Type -memberDefinition $f -name "EnumWindows" -namespace Win32Functions -passThru
$winList::EnumWindows(...)
我该如何正确地写下来?我有声明并传递参数吗?
可能有像this这样的方法吗?我正在寻找方法,其中 c# 仅用于声明 EnumWindows 函数,并使用正确的参数从 posh 调用它。
【问题讨论】:
标签:
.net
powershell
winapi
【解决方案1】:
完成这项工作需要几件事:
- 定义
EnumWindowsProc委托
- 制作
EnumWindows()public(或编写一个公共方法来包装对EnumWindows()的调用)
您也可以在 C# 中实现回调函数,也可以使用 PowerShell 脚本块。
以下是我将如何使用脚本块进行操作:
$MemberDefinition = @'
// declare the EnumWindowsProc delegate type
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
// Notice EnumWindows() is now `public`
[DllImport("user32.dll")]
public static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
'@
Add-Type -MemberDefinition $MemberDefinition -Name EnumWindowsUtil -Namespace Win32Functions
# Create a list to act as a receptacle for all the window handles we're about to enumerate
$WindowHandles = [System.Collections.Generic.List[IntPtr]]::new()
# Define the callback function
$callback = {
param([IntPtr]$handle, [IntPtr]$param)
# Copy the window handle to our list
$WindowHandles.Add($handle)
# Continue (return $false from the callback to abort the enumeration)
return $true
}
if([Win32Functions.EnumWindowsUtil]::EnumWindows($callback, [IntPtr]::Zero)){
# $WindowHandles will contain all the window handles now
}