C#实现从应用打开的Word/其他窗口前置失败问题问询
问题:打开关联文件时窗口无法始终前置
我在应用中打开Word文档(或其他程序关联的文件)时,希望其窗口能显示在最前端,但有时窗口会停留在后台。已做过相关研究但未解决问题。
初始代码
Process fileopener = new Process(); fileopener.StartInfo.FileName = "explorer"; fileopener.StartInfo.Arguments = $"\"{filePath}\""; fileopener.Start(); IntPtr intPtr = fileopener.MainWindowHandle;
尝试过的两种无效方案
1. 简单方案(无效)
ShowWindowAsync(intPtr ,3); SetForegroundWindow(intPtr);
2. 复杂方案(无效)
多篇文章指出简单方案无效的原因是Win32 API的限制,系统仅允许满足特定条件的进程设置前台窗口,条件包括:
- 进程为前台进程
- 进程由前台进程启动
- 进程接收了最后一个输入事件
- 无前台进程
- 前台进程正在被调试
- 前台未锁定(参考LockSetForegroundWindow)
- 前台锁超时已过期(参考SystemParametersInfo中的SPI_GETFOREGROUNDLOCKTIMEOUT)
- 无活动菜单
参考相关文章重写代码如下:
uint currentThread = (uint)Thread.CurrentThread.ManagedThreadId; IntPtr activeWindow = GetForegroundWindow(); IntPtr processId = new IntPtr(); uint activeThread = GetWindowThreadProcessId(activeWindow, processId); IntPtr windowProcess = new IntPtr(); uint windowThread = GetWindowThreadProcessId(window, windowProcess); if (currentThread != activeThread) AttachThreadInput(currentThread, activeThread, true); if (windowThread != currentThread) AttachThreadInput(windowThread, currentThread, true); uint oldTimeout = 0, newTimeout = 0; SystemParametersInfo(0x2001, 0, (IntPtr)oldTimeout, 0); SystemParametersInfo(0x2001, 0, (IntPtr)newTimeout, 0); LockSetForegroundWindow(2); AllowSetForegroundWindow(uint.MaxValue); ShowWindow(window, 9); SetForegroundWindow(window); SystemParametersInfo(0x2001, 0, (IntPtr)oldTimeout, 0); if (currentThread != activeThread) AttachThreadInput(currentThread, activeThread, false); if (windowThread != currentThread) AttachThreadInput(windowThread, currentThread, false); int errorCode = Marshal.GetLastWin32Error(); v($"Error bringing window to foreground: {errorCode}");
该代码未达预期效果,且获取到Win32错误码1300(权限检查失败),不确定是否仍能通过编程方式将窗口前置。
更新1
根据评论修改了代码,但仍无效,进程启动后并非始终处于前台:
Process p = new Process(); p.StartInfo.UseShellExecute = true; p.StartInfo.FileName = filePath; p.Start(); IntPtr intPtr = p.MainWindowHandle; SetForegroundWindow(intPtr); ForceWindowIntoForeground(intPtr);
内容的提问来源于stack exchange,提问作者Šimon Cerman
相关产品推荐
相关产品推荐

