万一多个应用程序实例正在运行,如何获取应用程序的活动/前景实例?

时间:2019-03-01 07:28:30

标签: c# windows getforegroundwindow

我正在尝试与用户正在工作的Visual Studio应用程序实例进行交互,即前台的应用程序实例。我正在使用GetActiveObject()获取VS的实例。但是,如果有多个VS实例在运​​行,它将始终给出第一个实例(首先打开的实例)。

我尝试使用AccessibleObjectFromWindow()和Spy ++来获得VS的Window类作为“ HwndWrapper”,但“ hr”值却为负。

下面是代码:

if (hwnd != null)
{
    EnvDTE80.DTE2 dte = null;
    int hwndChild = 0;
    EnumChildCallback cb = new EnumChildCallback(EnumVisualStudioChildProc);
    EnumChildWindows(hwnd.ToInt32(), cb, ref hwndChild);
    if (hwndChild != 0)
    {
        const uint OBJID_NATIVEOM = 0xFFFFFFF0;
        Guid IID_IDispatch = new Guid("{00020400-0000-0000-C000-000000000046}");
        int hr = AccessibleObjectFromWindow(hwndChild, OBJID_NATIVEOM, IID_IDispatch.ToByteArray(), out IDispatch ptr);
        if (hr >= 0)
        {
            dte = (EnvDTE80.DTE2)ptr.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, ptr, null);
        }
        else
        {
            Console.WriteLine("hr count " + hr + "\n");
        }
    }
    else
    {
        Console.WriteLine("hwndChild count " + hwndChild + "\n");
        dte = (EnvDTE80.DTE2)Marshal.GetActiveObject("VisualStudio.DTE." + VisualStudio.GetInstances());
    }
}

public static bool EnumVisualStudioChildProc(int hWnd, ref int lParam)
{
    StringBuilder buf = new StringBuilder(128);
    GetClassName(hWnd, buf, 128);
    if (buf.ToString().Contains("HwndWrapper"))
    {
        lParam = hWnd;
        return false;
    }
    return true;
}

我尝试了类似的方法来查找Word(类名:_Wwg)/ Excel的前台实例,它也可以正常工作,我用来检索窗口的类名是否正确?

2 个答案:

答案 0 :(得分:2)

一种解决方案是使用UI Automation。因此,您需要添加对UIAutomationClientUIAutomationTypes的引用,然后使用类似以下示例的代码:

// get the foreground window handle.
// here I used the Windows GetForegroundWindow function but you can use
// any function that defines what is the active/foreground window in your context
var foreground = GetForegroundWindow();

// get all Visual Studio main windows (from the desktop)
foreach (AutomationElement child in AutomationElement.RootElement.FindAll(
    TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "VisualStudioMainWindow")))
{
    // note the unfortunate 32-bit that UI automation uses instead of IntPtr...
    // in practise that shouldn't be a problem
    if (child.Current.NativeWindowHandle == foreground.ToInt32())
    {
        // this is the foreground Visual Studio
        // get its DTE instance
        var obj = GetVisualStudioInstance(child.Current.ProcessId);        
    }
}

// see doc at https://docs.microsoft.com/en-us/previous-versions/ms228755(v=vs.140)
public static object GetVisualStudioInstance(int processId)
{
    CreateBindCtx(0, out var ctx);
    if (ctx == null)
        return null;

    ctx.GetRunningObjectTable(out var table);
    table.EnumRunning(out var enumerator);
    var monikers = new IMoniker[1];
    while (enumerator.Next(1, monikers, IntPtr.Zero) == 0)
    {
        monikers[0].GetDisplayName(ctx, null, out var name);
        if (Regex.Match(name, @"!VisualStudio.DTE\.[0-9]*\.[0-9]*:" + processId).Success)
        {
            table.GetObject(monikers[0], out var obj);
            return obj;
        }
    }
    return null;
}


[DllImport("user32")]
private static extern IntPtr GetForegroundWindow();

[DllImport("ole32")]
private static extern int CreateBindCtx(int reserved, out IBindCtx ppbc); // from System.Runtime.InteropServices.ComTypes

答案 1 :(得分:-1)

我想它应该起作用:

   var processName = "devenv";
   var active = Process.GetProcessesByName(searchName).OrderByDescending(x =>  x.Threads.OfType<ProcessThread>().Count(t => t.ThreadState != ThreadState.Wait)).FirstOrDefault();

重点是按线程状态活动状态进行过滤: t.ThreadState != ThreadState.Wait只是为了简化。

对于当前正在运行的应用程序,解决方案是:

        IntPtr hwnd = GetForegroundWindow();
        uint pid;
        GetWindowThreadProcessId(hwnd, out pid);
        Process p = Process.GetProcessById((int)pid);
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

但第二个示例仅确定当前正在运行的应用程序进程