I'm trying to interact with Visual Studio's application instance in which the user is working i.e. the one in the foreground. I'm using GetActiveObject() to get the instance of VS. But, in case there are multiple instances of VS running, it always gives the first instance (the one which was opened first).
I tried using AccessibleObjectFromWindow() and using Spy++ I got the Window Class for VS as "HwndWrapper", but the "hr" value is getting negative.
Below is the code:
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;
}
I tried similar approach for finding the foreground instance of Word (Class name: _Wwg) /Excel also, there its working, Is class name I am using to retrieve the window correct?