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

时间:2012-12-14 15:30:58

标签: c# .net windows

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

4 个答案:

答案 0 :(得分:5)

通常的方法是:

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

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

我使用How To Enumerate Windows Using the 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);

}

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

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

您可以选择check the Windows Caption

  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))

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

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

关于myTopForm.TopMost = true答案,这对外部应用程序无效。

答案 1 :(得分:1)

它与“进程”无关,与Windows焦点有关。

你可能会做这样的事情:

http://msdn.microsoft.com/en-us/library/3saxwsad.aspx

public void MakeOnTop()
{
  myTopForm.TopMost = true;
}

但总的来说,你需要Window句柄(衍生过程可以很容易地找出它自己的句柄),你需要这样的东西:

http://support.microsoft.com/kb/186431

答案 2 :(得分:0)

您可以尝试使用SetWindowPos api调用将窗口发送到Windows中z顺序的BACK。

http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545(v=vs.85).aspx

[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, uint wFlags);

const UInt32 SWP_NOSIZE = 0x0001;
const UInt32 SWP_NOMOVE = 0x0002;

static readonly IntPtr HWND_BOTTOM = new IntPtr(1);

static void SendWindowBack()
{
    var hWnd = this.Handle;
    SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
}

(用于winforms而不是wpf的编辑。)

答案 3 :(得分:0)

没有直接且100%可靠的方法来做到这一点。我会以一种稍微迂回的方式解决这个问题:

获取您启动的进程的进程ID,然后使用EnumWindows函数的C#等效项。在回调中,调用GetWindowThreadProcessId以获取窗口的进程ID,将其与刚刚启动的窗口的进程ID进行比较。如果匹配,则可以使用SetForegroundWindow将该窗口置于前台。

如果有问题的应用程序显示多个顶级窗口,则会找到第一个窗口,这可能不是正确的窗口。但是,如果没有来自应用程序的某些“合作”,我认为我概述的是你能做的最好的。