Unfortunately, this is not easily possible when accessing a window created by another program, because the system doesn't do the necessary window message marshalling of pointers. You would need to do this from a shared DLL file (create some system-wide Windows Hook in it to load it into other processes) or using other hacks like inter-process memory access.
If accessing a SysHeader32 window in the same program, it would be simple as this:
Send message
HDM_GETITEMCOUNT
, it returns the number of items.Send message
HDM_GETITEM
withwParam
set to the index of the item to retrieve andlParam
set to a pointer to appropriately setHDITEM
structure. Particularly setmask
toHDI_TEXT
and prepare a buffer forpszText
and set its length in tocchTextMax
.
Example:
int count = SendMessage(hWnd, HDM_GETITEMCOUNT, 0, 0);
std::cout << "There are " << count << " items.\n";
for (int i = 0; i < count; i++) {
TCHAR name[260];
HDITEM hdi;
hdi.mask = HDI_TEXT;
hdi.pszText = name;
hdi.cchTextMax = 260;
SendMessage(hWnd, HDM_GETITEM, i, reinterpret_cast<LPARAM>(&hdi));
std::cout << " " << i << ") " << hdi.pszText << "\n";
}
Because we need to store the input and output memory in another program's space, something like this is necessary (please add error checking etc. according to your liking):
struct InterProcessData {
HDITEM hdi;
TCHAR buffer[260];
};
// Open the owning process and allocate a buffer big enough for
// our inter-process communication
DWORD dwProcessId;
GetWindowThreadProcessId(hWnd, &dwProcessId);
HANDLE hProcess = OpenProcess(
PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE,
FALSE, dwProcessId);
InterProcessData* pRemoteData = reinterpret_cast<InterProcessData*>(
VirtualAllocEx(hProcess, NULL, sizeof(InterProcessData), MEM_COMMIT, PAGE_READWRITE));
int count = SendMessage(hWnd, HDM_GETITEMCOUNT, 0, 0);
std::cout << "There are " << count << " items.\n";
for (int i = 0; i < count; i++) {
InterProcessData data;
data.hdi.mask = HDI_TEXT;
data.hdi.pszText = pRemoteData->buffer;
data.hdi.cchTextMax = 260;
// Write the HDITEM structure to the space in the remote process
// (without the buffer, its contents are undefined anyway)
WriteProcessMemory(hProcess, pRemoteData, &data, sizeof(data.hdi), NULL);
// Send the message itself, passing the remote address in lParam
SendMessage(hWnd, HDM_GETITEM, i, reinterpret_cast<LPARAM>(&pRemoteData->hdi));
// Read the data back, HDITEM and the buffer
ReadProcessMemory(hProcess, pRemoteData, &data, sizeof(data), NULL);
// The documentation says that the pszText can point elsewhere -
// copy it to our buffer in that case
if (data.hdi.pszText != pRemoteData->buffer)
ReadProcessMemory(hProcess, data.hdi.pszText, data.buffer, data.hdi.cchTextMax * sizeof(TCHAR), NULL);
std::cout << " " << i << ") " << data.buffer << "\n";
}
// Cleanup
VirtualFreeEx(hProcess, pRemoteData, 0, MEM_RELEASE);
CloseHandle(hProcess);