Abhijit
Abhijit

Reputation: 63767

Selecting and Highlighting an Item from List View

I would like to select and highlight an item from a list view control and am using the following code

#include <Windows.h>
#include <commctrl.h>


int main() {
    //Hardcoded Handle to the ListView Windows of Add Printer Dialog
    HWND hwndListView = (HWND)0x000206D6; 
    DWORD dwProcessID;
    ::GetWindowThreadProcessId( hwndListView, &dwProcessID );
    HANDLE process=OpenProcess(PROCESS_VM_OPERATION|PROCESS_VM_READ|PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION, FALSE, dwProcessID); 

    LVITEM lvi;

    LVITEM* _lvi=(LVITEM*)VirtualAllocEx(process, NULL, sizeof(LVITEM), MEM_COMMIT, PAGE_READWRITE); 

    lvi.state = LVIS_FOCUSED | LVIS_SELECTED ;
    lvi.stateMask = LVIS_FOCUSED | LVIS_SELECTED ;
    lvi.mask = LVIF_STATE;

    WriteProcessMemory(process, _lvi, &lvi, sizeof(LVITEM), NULL); 
    ::SendMessage(hwndListView, LVM_SETITEMSTATE, (WPARAM)0, (LPARAM)_lvi); 
    VirtualFreeEx(process, _lvi, 0, MEM_RELEASE);
}

The result I am getting is

enter image description here

instead of the item getting selected and highlighted

enter image description here

Please let me know what might be going wrong

Upvotes: 1

Views: 1952

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597215

There are restrictions on which processes can set focus on a window, and chances are that the app selecting the ListView items does not satisfy those restrictions while the dialog is active. For example, the HWND being focused must be attached to the calling thread's message queue. So the highlighting app will have to use AttachThreadInput() before calling SetFocus() on another app's windows.

Upvotes: 2

Related Questions