回复 4# yakeyun
我稍微改了一下代码, 改成了关闭标题文本以 __888__ 开头的窗口,
刚试了一下, 还是不行, 代码执行完, 有很大机率, 窗口仍然没关闭- Add-Type @"
- using System;
- using System.Text;
- using System.Runtime.InteropServices;
- public class Win32 {
- [DllImport("user32.dll", SetLastError=true)]
- public static extern int EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
- public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
- [DllImport("user32.dll", SetLastError=true)]
- public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
- [DllImport("user32.dll", SetLastError=true)]
- public static extern int GetWindowTextLength(IntPtr hWnd);
- [DllImport("user32.dll", SetLastError=true)]
- public static extern bool IsWindowVisible(IntPtr hWnd);
- [DllImport("user32.dll", SetLastError=true)]
- public static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
- [DllImport("user32.dll", SetLastError=true)]
- public static extern bool IsWindow(IntPtr hWnd);
- }
- "@
- $WM_CLOSE = 0x0010
- $target = "__888__"
- # 函数:检查窗口是否存在
- function Test-WindowExists {
- param($windowTitle)
- $exists = $false
- [Win32+EnumWindowsProc]$checkCallback = {
- param($hWnd, $lParam)
- if ([Win32]::IsWindowVisible($hWnd)) {
- $length = [Win32]::GetWindowTextLength($hWnd)
- if ($length -gt 0) {
- $builder = New-Object System.Text.StringBuilder $length
- [Win32]::GetWindowText($hWnd, $builder, $length + 1) | Out-Null
- $title = $builder.ToString()
- if ($title.StartsWith($windowTitle)) {
- $exists = $true
- return $false # 停止枚举
- }
- }
- }
- return $true
- }
- [Win32]::EnumWindows($checkCallback, [IntPtr]::Zero) | Out-Null
- return $exists
- }
- # 主关闭逻辑
- do {
- $windowFound = $false
- [Win32+EnumWindowsProc]$callback = {
- param($hWnd, $lParam)
- if ([Win32]::IsWindowVisible($hWnd)) {
- $length = [Win32]::GetWindowTextLength($hWnd)
- if ($length -gt 0) {
- $builder = New-Object System.Text.StringBuilder $length
- [Win32]::GetWindowText($hWnd, $builder, $length + 1) | Out-Null
- $title = $builder.ToString()
- if ($title.StartsWith($target)) {
- $windowFound = $true
- [Win32]::PostMessage($hWnd, $WM_CLOSE, 0, 0) | Out-Null
- Write-Host "尝试关闭窗口:$title"
- }
- }
- }
- return $true
- }
- [Win32]::EnumWindows($callback, [IntPtr]::Zero) | Out-Null
-
- if ($windowFound) {
- # 等待一会儿让窗口有机会关闭
- Start-Sleep -Milliseconds 500
- } else {
- Write-Host "未找到目标窗口,退出循环"
- break
- }
- } while (Test-WindowExists -windowTitle $target)
复制代码 |