UI自动化在C ++ / CLI和C#之间的工作方式不同,为什么?

时间:2018-10-19 22:04:05

标签: ui-automation

这是两个相同的应用程序。它们分别用C ++ / CLI和C#编写。

问题 为什么UI Api对于相同的窗口和几乎相同的代码显示不同的结果?该代码似乎无法正确读取UI树。

C ++ / CLI代码

#include "stdafx.h"


using namespace System;

void MarshalString(String ^ s, std::string& os);

int main(array<System::String ^> ^args)
{
    std::string p;
    std::string s;
    HWND hWnd = (HWND)0x005D0B52;
    AutomationElement^ ele = AutomationElement::FromHandle(IntPtr(hWnd));

    TreeWalker ^pWalk = TreeWalker::ControlViewWalker;

    AutomationElement^ pNode = pWalk->GetFirstChild(ele);

    while (pNode) {
        String^ localCT = pNode->Current.LocalizedControlType;
        MarshalString(localCT, s);
        std::cout << "Localized string: " << s << std::endl;
        pNode = pWalk->GetNextSibling(pNode);
    }

    std::cin >> p;

    return 0;
}

void MarshalString(String ^ s, std::string& os) {
    using namespace Runtime::InteropServices;
    const char* chars =
        (const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
    os = chars;
    Marshal::FreeHGlobal(IntPtr((void*)chars));
}

C#代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Automation;

namespace ConsoleApp10
{
    class Program
    {
        static void Main(string[] args)
        {
            IntPtr ptr = new IntPtr(0x005D0B52);
            AutomationElement ele = AutomationElement.FromHandle(ptr);
            if (ele != null)
            {
                TreeWalker pWalk = TreeWalker.ControlViewWalker;

                AutomationElement pNode = pWalk.GetFirstChild(ele);

                while (pNode!=null)
                {
                    Console.WriteLine($"Control Type = {pNode.Current.LocalizedControlType}");
                    pNode = pWalk.GetNextSibling(pNode);
                }

                Console.Read();
            }
        }
    }
}

C ++ / CLI的输出 C++/CLI Output

C#的输出 C# output

0 个答案:

没有答案