Select an item in a SysListView32 control

i have the window handle of a SysListView32 control in an external application.  I want my program to select/highlight the item of index 3.  Any idea what the API is to do this?? Thanks

Who is Participating?
Option Explicit

Private Type LV_ITEM
    mask As Long
    iItem As Long
    iSubItem As Long
    state As Long
    stateMask As Long
    pszText As Long
    cchTextMax As Long
    iImage As Long
    lParam As Long
    iIndent As Long
End Type

Private Const LVM_FIRST = &H1000

Private Const LVIF_STATE = &H8
Private Const LVIS_FOCUSED = &H1
Private Const LVIS_SELECTED = &H2

Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal Msg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function WriteProcessMemory Lib "kernel32" (ByVal hProcess As Long, lpBaseAddress As Any, lpBuffer As Any, ByVal nSize As Long, lpNumberOfBytesWritten As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long, lpdwProcessId As Long) As Long
Private Declare Function VirtualAllocEx Lib "kernel32" (ByVal hProcess As Long, ByVal lpAddress As Long, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As Long
Private Declare Function VirtualFreeEx Lib "kernel32" (ByVal hProcess As Long, lpAddress As Any, ByVal dwSize As Long, ByVal dwFreeType As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Const MEM_COMMIT = &H1000
Private Const MEM_RESERVE = &H2000
Private Const MEM_RELEASE = &H8000

Private Const PAGE_READWRITE = &H4&

Public Sub SelectItemRemote(ByVal hLV As Long, ByVal itmNum As Long)
   Dim tid As Long, pid As Long, hProcess As Long
   Dim liAddr As Long, lWritten As Long
   Dim li As LV_ITEM
   tid = GetWindowThreadProcessId(hLV, pid)
   If pid = 0 Then Exit Sub
   hProcess = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
   If hProcess = 0 Then Exit Sub
   With li
      .mask = LVIF_STATE
      .state = True
   End With
   liAddr = VirtualAllocEx(hProcess, 0, Len(li), MEM_RESERVE Or MEM_COMMIT, PAGE_READWRITE)
   WriteProcessMemory hProcess, ByVal liAddr, li, Len(li), lWritten
   Call SendMessage(hLV, LVM_SETITEMSTATE, itmNum, ByVal liAddr)
   VirtualFreeEx hProcess, ByVal liAddr, 0, MEM_RELEASE
   If hProcess Then CloseHandle hProcess
End Sub

Private Sub Command1_Click()
   SelectItemRemote &H10092, 2 ' Note - lv items index zero based
End Sub
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.