如何使用C从点检索元素

问题描述

我有以下代码来检索桌面上特定位置的元素:

#include "UiAutomationclient.h"

iuiAutomation *pAutomation = NULL;
iuiAutomationElement *element = NULL;

CoInitialize(NULL);
      
EXTERN_C const CLSID CLSID_CUIAutomation;
EXTERN_C const IID IID_iuiAutomation;

HRESULT hr = CoCreateInstance(&CLSID_CUIAutomation,NULL,CLSCTX_INPROC_SERVER,&IID_iuiAutomation,(void**)&pAutomation);
if(SUCCEEDED(hr)){
  GetCursorPos(&pt);
  hr = pAutomation->ElementFromPoint(pt,&element);
  if(SUCCEEDED(hr) && element != NULL){

  }
  pAutomation->Release();
}
CoUninitialize();

编译后出现以下错误

'ElementFromPoint': is not a member of 'iuiAutomation'
'Release': is not a member of 'iuiAutomation'

由于我正在按照文档中的说明进行操作,因此我被困在这一点上。如果有人可以帮助我解决C中的错误,请提前告知。

解决方法

使用COM形式的C比使用C ++更为冗长,但没有根本区别。

使用C ++调用

HRESULT hr = com_interface->method( arguments );

转换为C的样子

HRESULT hr = com_interface->lpVtbl->method( com_interface,arguments );

只需在接口指针和方法名称之间放置->lpVtbl->而不是->,然后重复将接口指针作为第一个参数即可。

在C ++中

hr = pAutomation->ElementFromPoint(pt,&element);
...
pAutomation->Release();

在C

hr = pAutomation->lpVtbl->ElementFromPoint(pAutomation,pt,&element);
...
pAutomation->lpVtbl->Release(pAutomation);