gpt4 book ai didi

c# - SetForegroundWindow 不工作

转载 作者:行者123 更新时间:2023-11-30 18:29:07 24 4
gpt4 key购买 nike

我正在尝试启动一个应用程序并将其置于最前面。但是,应用程序启动正常,但最终会落后启动应用程序。请注意,在已运行的最小化应用程序上使用类似的方法效果很好(为简洁起见,从该示例中删除了该代码)——它仅在启动应用程序的新实例时才会失败。有任何想法吗?谢谢

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace Launcher
{
class Program
{
[DllImport("User32.dll", SetLastError = true)]
private static extern int SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);

[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

private const int SW_SHOWMAXIMIZED = 3;

private static readonly IntPtr HWND_TOP = new IntPtr(0);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 SWP_SHOWWINDOW = 0x0040;

static void Main(string[] args)
{
string wd = @"C:\Program Files (x86)\MyFolder";

string fn = "MyApplication.exe";

if (!System.IO.File.Exists(wd + @"\" + fn)) return;

Process p = new Process();
p.StartInfo.WorkingDirectory = wd;
p.StartInfo.FileName = fn;

p.StartInfo.CreateNoWindow = false;
p.Start(); // app launches OK

Thread.Sleep(5000);

SetForegroundWindow(p.MainWindowHandle); // this has no effect
SetWindowPos(p.MainWindowHandle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
}
}
}
}

最佳答案

好的,在阅读了此处的更多问题后,我设法通过组合使用 WaitForInputIdle 和一个 do 循环来解决问题,该循环检查要设置的窗口标题(我在代码中这样做)以确保应用程序具有在调用 SetForegroundWindow 之前安定下来。希望这对其他人有帮助

关于c# - SetForegroundWindow 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23500086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com