c# - 如果多个应用程序实例正在运行,如何获取应用程序的事件/前台实例?

标签 c# windows getforegroundwindow

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

我尝试使用 AccessibleObjectFromWindow()并使用 Spy++ 我将 VS 的窗口类作为“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 的前台实例,它在那里工作,我用来检索窗口的类名是否正确?

最佳答案

一种解决方案是使用 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://learn.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

关于c# - 如果多个应用程序实例正在运行,如何获取应用程序的事件/前台实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54939867/

相关文章:

c# - WebClient.DownloadString() 结果在某些网站上存在编码问题!使用波斯语(波斯语)

javascript - 使用 Newtonsoft、C# 反序列化 JSON 时出错

windows - 如何从命令行运行 Windows Phone Store Cetrification Kit?

c# - 将文本写入文本框

windows - 如何使用批处理获取前景窗口?

c# - 从一个程序获取变量到另一个程序

c# - 获取未知类型的方法并运行它 c#

windows - 如何在 Windows 上创建虚拟网络接口(interface)?

winapi - "GetForegroundWindow: identifier not found"在 Visual Studio 2015