当MainWindowHandle为0时,将窗口置于前景

如果MainWindowHandle不为0,以下代码将窗口置于前台。

我怎样才能把一个窗口到MainWindowHandle = 0的前面?

这是为Microsoft Excel – 兼容性检查器窗口显示一个GUI,但没有任务栏中的图标,并具有MainWindowHandle = 0。

我没有其他Excel运行的实例。

 Add-Type @" using System; using System.Runtime.InteropServices; public class Tricks { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); } "@ $excel = (Get-Process | Where-Object { $_.ProcessName -eq 'EXCEL' }).MainWindowHandle [void] [Tricks]::SetForegroundWindow($excel) 

在Windows任务pipe理器中,我可以右键单击“Microsoft Excel – 兼容性检查器”,然后单击“带到前面”,并工作。 如何在Powershell中模仿这个function?

感谢IInspectable指引我在正确的方向。

这段代码得到了真正的MainWindowHandle值:

 $TypeDef2 = @" using System; using System.Text; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Api { public class WinStruct { public string WinTitle {get; set; } public int MainWindowHandle { get; set; } } public class ApiDef { private delegate bool CallBackPtr(int hwnd, int lParam); private static CallBackPtr callBackPtr = Callback; private static List<WinStruct> _WinStructList = new List<WinStruct>(); [DllImport("User32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool EnumWindows(CallBackPtr lpEnumFunc, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); private static bool Callback(int hWnd, int lparam) { StringBuilder sb = new StringBuilder(256); int res = GetWindowText((IntPtr)hWnd, sb, 256); _WinStructList.Add(new WinStruct { MainWindowHandle = hWnd, WinTitle = sb.ToString() }); return true; } public static List<WinStruct> GetWindows() { _WinStructList = new List<WinStruct>(); EnumWindows(callBackPtr, IntPtr.Zero); return _WinStructList; } } } "@ Add-Type -TypeDefinition $TypeDef2 -Language CSharpVersion3 $excelInstance = [Api.Apidef]::GetWindows() | Where-Object { $_.WinTitle.ToUpper() -eq "Microsoft Excel - Compatibility Checker".ToUpper() } 

所以现在使用这个正确的值,我可以调用SetForegroundWindow()函数:

 Add-Type @" using System; using System.Runtime.InteropServices; public class Tricks { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); } "@ [void] [Tricks]::SetForegroundWindow($excelInstance.MainWindowHandle) 

我在我的网站上写了一个详细的博客。

我已经在GitHub上提供了一个关于如何创build一个Excel文件的完整示例,编辑它,并在不同的线程中运行上面的代码,因为Excelpopup窗口会阻塞主线程。