C++ AccessibleObjectFromWindow always return 0

Phan Hoài Sơn 40 Reputation points
2023-06-23T04:28:31.2133333+00:00

Hello guys,

I'm new developer windows.
I want to get ROLE_SYSTEM_TEXT of application in window but I got trouble with function AccessibleObjectFromWindow
I read the docs and try to use this fuction but it not work
Please help me fix it.
This is my code :

#include <iostream>
#include <Windows.h>
#include <OleAcc.h>
#include <unistd.h>


void get_role_system_text(){
  HWND hwnd = GetActiveWindow();
  IAccessible* pAccessible = nullptr;
    VARIANT varChild;
    varChild.vt = VT_EMPTY;

    HRESULT hr = AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, (void**)&pAccessible);
    std::cout << "AccessibleObjectFromWindow pAccessible : " << pAccessible << std::endl;
    std::cout << "AccessibleObjectFromWindow SUCCEEDED(hr) : " << SUCCEEDED(hr) << std::endl;

    if (SUCCEEDED(hr)) {
        VARIANT varRole;
        hr = pAccessible->get_accRole(varChild, &varRole);
        if (SUCCEEDED(hr) && varRole.vt == VT_I4) {
            std::cout << "Role value: " << varRole.lVal << std::endl;
        }
        pAccessible->Release();
    }
}

int main() {
    // Initialize COM
    CoInitialize(nullptr);

    while(1){
        Sleep(1000);
        get_role_system_text();
    }

    // Uninitialize COM
    CoUninitialize();

    return 0;
}

Comand build: g++ role.cpp -loleacc -lole32

Windows development | Windows API - Win32
Developer technologies | C++
Developer technologies | C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 91,416 Reputation points
    2023-06-23T05:22:54.79+00:00

    This is a Console code and hwnd is probably NULL

    Call

     HWND hwnd = GetConsoleWindow();
    

    instead to get the Console window

    or

    HWND hwnd = GetForegroundWindow();
    
    

    for the foreground window

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.