Search code examples
delphiui-automationmicrosoft-ui-automationtypelib

Delphi: missing interface declarations for UI Automation methods


Such a basic question, but I'm stuck...

I'm trying to get started with UI Automation using Delphi 2007 (Win32) on Windows 7. It seems I don't have declarations for some of the methods and types I need to use. I have .NET Framework 4.x installed on this machine, but I imported a type library from C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationClient.dll...which in UIAutomationClient_TLB.pas I see is:

UIAutomationClientMajorVersion = 1;
UIAutomationClientMinorVersion = 0;

I'm not sure if that's the problem (wrong version). I can declare the following with no problem:

var
  UIAuto: IUIAutomation;
  Element: IUIAutomationElement;

But methods of IUIAutomationElement appear to be missing. For instance, there's nothing in the interface declaring the method:

    IUIAutomationElement.TryGetCurrentPattern()

...which, according to msdn.microsoft.com is an interface method going back to at least .NET 3.0.

Where / how do I get the necessary interface declarations? Is this possibly a registration problem? If so, what needs to be registered, and how?

Ultimately, I'm wanting to play with retrieving text from controls via UI Automation with something like the following, but technically speaking, I think you have to get code to compile before you can consider it a failure. ;)

var
  UIAuto: IUIAutomation;
  Element: IUIAutomationElement;
  RetVal: HResult;
  APattern: AutomationPattern;    //not defined!
  ValuePattern : ValuePattern;    //not defined!
begin
  UIAuto := CoCUIAutomation.Create;
  Element := UIAuto.GetFocusedElement(RetVal);
  if Assigned(Element) then begin
    if Element.TryGetCurrentPattern(ValuePattern.Pattern, APattern) then begin  //not defined!
      Result := ValuePattern.Current.Value;                                     //not defined!
  ...

end;

Solution

  • It looks like you have imported the .net assembly.

    From native code it is best to import the native COM type library. The steps are:

    1. Component | Import Component.
    2. Import a Type Library.
    3. Select UIAutomationClient which is implemented in UIAutomationCore.dll.

    This imports a type library and creates a unit named UIAutomationClient_TLB.

    The method that you need is IUIAutomationElement.GetCurrentPattern. The TryGetCurrentPattern method in the .net version of the interface is simply a convenience method that indicates failure with a boolean return value rather than by raising an exception. When you call IUIAutomationElement.GetCurrentPattern you will need to check the HRESULT return value to detect failure.