确保衍生进程的窗口位于主应用程序的前面?

jap*_*iss 3 .net c# windows

在我的GUI应用程序中,我使用C#Process类来生成可能启动窗口的外部进程.子进程窗口可以通过第三方API调用显示,因此并不总是可以获得窗口句柄.有没有办法确保子进程的窗口显示在主应用程序窗口的前面?

Jer*_*son 5

通常的方法是:

1.获取Process.Start()返回的Process类实例
2.查询Process.MainWindowHandle
3.调用非托管Win32 API函数"ShowWindow"或"SwitchToThisWindow"

您的问题的诀窍是"子进程窗口可能通过第三方API调用显示".在这种情况下,您将需要获取生成的exe和Enum Child Windows的窗口句柄.获得API调用后显示的表单的句柄后,您可以使用BringWindowToTop API.

我使用如何枚举Windows使用WIN32 API作为灵感来组合一个小测试.使用1个表单和2个按钮创建Windows应用程序:

public partial class Form1 : Form
{
[DllImport("user32.dll", SetLastError = true)]
static extern bool BringWindowToTop(IntPtr hWnd);

[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);

public Form1()
{
    InitializeComponent();
}

private System.IntPtr hWnd;
private void button1_Click(object sender, EventArgs e)
{
    Process p = Process.Start(@"C:\TFS\Sandbox\3rdPartyAppExample.exe");         
    try
    {
        do
        {
            p.Refresh();
        }
        while (p.MainWindowHandle.ToInt32() == 0);

        hWnd = new IntPtr(p.MainWindowHandle.ToInt32());
    }
    catch (Exception ex)
    {
        //Do some stuff...
        throw;
    }
}

private void button2_Click(object sender, EventArgs e)
{
    3rdPartyAppExample.Form1 f = new 3rdPartyAppExample.Form1();
    f.ShowForm2();
    //Bring main external exe window to front
    BringWindowToTop(hWnd);
    //Bring child external exe windows to front
    BringExternalExeChildWindowsToFront(hWnd);
}

private void BringExternalExeChildWindowsToFront(IntPtr parent)
{
    List<IntPtr> childWindows = GetChildWindows(hWnd);
    foreach (IntPtr childWindow in childWindows)
    {
        BringWindowToTop(childWindow);
    }
}

// <summary>
/// Returns a list of child windows
/// </summary>
/// <param name="parent">Parent of the windows to return</param>
/// <returns>List of child windows</returns>
public static List<IntPtr> GetChildWindows(IntPtr parent)
{
    List<IntPtr> result = new List<IntPtr>();
    GCHandle listHandle = GCHandle.Alloc(result);
    try
    {
        EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
        EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
    }
    finally
    {
        if (listHandle.IsAllocated)
            listHandle.Free();
    }
    return result;
}

/// <summary>
/// Callback method to be used when enumerating windows.
/// </summary>
/// <param name="handle">Handle of the next window</param>
/// <param name="pointer">Pointer to a GCHandle that holds a reference to the list to fill</param>
/// <returns>True to continue the enumeration, false to bail</returns>
private static bool EnumWindow(IntPtr handle, IntPtr pointer)
{
    GCHandle gch = GCHandle.FromIntPtr(pointer);
    List<IntPtr> list = gch.Target as List<IntPtr>;
    if (list == null)
    {
        throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
    }
    list.Add(handle);
    //  You can modify this to check to see if you want to cancel the operation, then return a null here
    return true;
}

/// <summary>
/// Delegate for the EnumChildWindows method
/// </summary>
/// <param name="hWnd">Window handle</param>
/// <param name="parameter">Caller-defined variable; we use it for a pointer to our list</param>
/// <returns>True to continue enumerating, false to bail.</returns>
public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);

}
Run Code Online (Sandbox Code Playgroud)

3rdPartyAppExample是一个包含2个表单的Winform应用程序.我引用此应用程序并调用Form1的Public方法来显示Form2:

public partial class Form1 : Form
{        
    public Form1()
    {
        InitializeComponent();
    }
    public void ShowForm2()
    {
        var f = new Form2();
        f.Show();
    }
Run Code Online (Sandbox Code Playgroud)

您可以选择查看Windows标题:

  hInst = ProcessStart("calc.exe")

  // Begin search for handle
  hWndApp = GetWinHandle(hInst)

  If hWndApp <> 0 Then
   // Init buffer
   buffer = Space$(128)

   // Get caption of window
   numChars = GetWindowText(hWndApp, buffer, Len(buffer))
Run Code Online (Sandbox Code Playgroud)

另一个解决方案(不太稳定)在这里讨论:http: //www.shloemi.com/2012/09/solved-setforegroundwindow-win32-api-not-always-works/

诀窍是通过附加线程(使用AttachThreadInput API)让windows'认为'我们的进程和目标窗口(hwnd)是相关的.

关于myTopForm.TopMost = true答案,这对外部应用程序不起作用.