#include once "window9.bi"

Function AddListViewItem(ByVal gadget As Long, ByRef string_ As USTRING,ByVal IDImage_ As HBITMAP,ByVal pos_ As Long,_
ByVal SubItem_ As Long,ByVal Mask_item As Long=LVIF_TEXT Or LVIF_IMAGE) As integer Export
    dim  LVITEM9 As LVITEM
    dim as hwnd hWin = GadgetID(gadget)
    dim as any ptr pStackIndexes = GetProp(hWin, "stackindexes")
    dim as HIMAGELIST iList = Cast(HIMAGELIST,GetHimageCombo_(gadget))
    Dim As Integer iIndex
    If IDImage_<>0 Then
        if pStackIndexes andalso SizeStackFreeIndexes(pStackIndexes) then
            iIndex = PopStackFreeIndexes(pStackIndexes)
            ImageList_Replace(iList,iIndex,IDImage_,0)
        else
            iIndex=ImageList_Add(iList,Cast(HBITMAP,IDImage_),0)
        EndIf
    Else 
        iIndex=-2
    EndIf
    If string_="" Then string_=" "
    with LVITEM9
        .mask       = Mask_item
        .iItem      = pos_
        .iSubItem   = SubItem_
        .iImage     = iIndex
        #Ifdef UNICODE
            .pszText    = cast(any ptr , *string_)
        #Else
            .pszText    = StrPtr(string_)
        #EndIf   
        .cchTextMax = Len(string_)
    end with
    Dim As Integer send_
    If SubItem_=0 Then
        send_=SendMessage(hWin,LVM_INSERTITEM,0,Cast(LPARAM,@LVITEM9))
    Else
        send_=SendMessage(hWin,LVM_SETITEM,0,Cast(LPARAM,@LVITEM9))
    EndIf
    If iIndex <> -2 Then
        Function = iIndex
    Else
        Function = -1
    EndIf
End Function
