3

我正在尝试启动一个应用程序并将其放在前面。但是,应用程序启动正常,然后最终落后于启动应用程序。请注意,在已经运行的最小化应用程序上使用类似的方法可以正常工作(为简洁起见,从该示例中删除了该代码) - 它仅在启动应用程序的新实例时无法工作。有任何想法吗?谢谢

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);
        }
    }
}
}
4

1 回答 1

0

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

于 2016-01-05T10:30:11.270 回答