Share via


Win32: Setting the accessible name on a list item

This article is referenced directly by Microsoft Accessibility Insights for Windows. Microsoft Accessibility Insights for Windows can help spotlight many accessibility issues in UI, and guide you to the relevant UI framework-specific code sample to help you resolve the issue. Learn more about Microsoft Accessibility Insights for Windows.

Problem

When a screen reader encounters a list item in a ListView created with an image list, it may not announce the purpose of the item. This means my customers are blocked from whatever functionality is associated with the items.

Suggested Fix

Consider using the SetHwndPropStr() function to set helpful, concise, unambiguous and localized accessible names on all of the list items.

Code Sample: Setting the list items' accessible name explicitly.

Important: The sample below relates to ListView created with an image list.

// At the top of the C++ file.
#include <initguid.h> 
#include "objbase.h"
#include "uiautomation.h" 
IAccPropServices* _pAccPropServices = NULL;


// Run when the UI is created.
HRESULT hr = CoCreateInstance(
    CLSID_AccPropServices,
    nullptr,
    CLSCTX_INPROC,
    IID_PPV_ARGS(&_pAccPropServices));
if (SUCCEEDED(hr))
{
    for (int i = 0; (i < itemCount) && SUCCEEDED(hr); i++)
    {
        // Load up the localized accessible name for the item.
        WCHAR szName[MAX_LOADSTRING];
        LoadString(
            hInst,
            IDS_LISTVIEW_ITEM_START + i,
            szName,
            ARRAYSIZE(szName));

        // Now set the accessible name of the item.
        hr = _pAccPropServices->SetHwndPropStr(
            hWndListView,
            OBJID_CLIENT,
            i + 1, // One-based index of the item of interest.
            Name_Property_GUID,
            szName);
    }
}


// Run when the UI is destroyed.
if (_pAccPropServices != nullptr)
{
    MSAAPROPID props[] = { Name_Property_GUID };

    int itemCount = (IDS_LISTVIEW_ITEM_END - IDS_LISTVIEW_ITEM_START + 1);

    for (int i = 0; i < itemCount; i++)
    {
        // Clear the custom accessible name set earlier on the control.
        _pAccPropServices->ClearHwndProps(
            hWndListView,
            OBJID_CLIENT,
            i + 1, // One-based index of the item of interest.
            props,
            ARRAYSIZE(props));
    }

    _pAccPropServices->Release();
    _pAccPropServices = NULL;
}