代码示例:
using System;
using System.Runtime.InteropServices;
class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct GUID
{
public int Data1;
public short Data2;
public short Data3;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] Data4;
}
public static readonly GUID IID_IAccessible = new GUID
{
Data1 = 0x618736e0,
Data2 = 0x3c3d,
Data3 = 0x11cf,
Data4 = new byte[] { 0x96, 0xb8, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00 }
};
[DllImport("oleacc.dll")]
public static extern int AccessibleObjectFromWindow(IntPtr hwnd, uint id, ref GUID rid, [MarshalAs(UnmanagedType.LPVoid)] out IntPtr pAcc);
[DllImport("oleacc.dll")]
public static extern int AccessibleChildren(IntPtr pAccParent, int iChildStart, int cChildren, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] IntPtr[] rgvarChildren, out int pcObtained);
[DllImport("oleacc.dll")]
public static extern int AccName(IntPtr pAcc, int childID, out IntPtr pszName);
[DllImport("oleacc.dll")]
public static extern int AccLocation(out int pxLeft, out int pyTop, out int pcxWidth, out int pcyHeight, IntPtr pAcc, int childID);
static void Main(string[] args)
{
// 获取目标应用程序的窗口句柄(HWND),这里假设你已经有了目标窗口的句柄
IntPtr hwnd = ...; // 替换为目标窗口的句柄
IntPtr pAcc;
if (AccessibleObjectFromWindow(hwnd, 0, ref IID_IAccessible, out pAcc) == 0)
{
PrintControlTreeMSAA(pAcc,0);
}
}
static void PrintControlTreeMSAA(IntPtr pAcc, int depth)
{
int childCount;
AccessibleChildren(pAcc, 0, 0, null, out childCount);
IntPtr[] children = new IntPtr[childCount];
AccessibleChildren(pAcc, 0, childCount, children, out _);
for (int i = 0; i < childCount; i++)
{
IntPtr childNamePtr;
if (AccName(pAcc, i, out childNamePtr) == 0)
{
string childName = Marshal.PtrToStringUni(childNamePtr);
Console.WriteLine(new string(' ', depth * 2) + " - " + childName);
Marshal.FreeCoTaskMem(childNamePtr);
}
PrintControlTreeMSAA(children[i], depth + 1);
}
}
}