SysTools Logo SysTools


C, WinAPI: Replace ListBox string by item index


// Replace ListBox string by item index with item data preservation and flickering prevention.
void LB_ReplaceString(HWND hListBox, LRESULT lIndex, TCHAR *lpString) {
LRESULT lSel, lTop, lDat;
  // minimal sanity checks
  if (hListBox && lpString && (lIndex >= 0)) {
    // disable any window redraw
    SendMessage(hListBox, WM_SETREDRAW, (WPARAM) FALSE, 0);
    // save current selection
    lSel = SendMessage(hListBox, LB_GETCURSEL, 0, 0);
    // save top index
    lTop = SendMessage(hListBox, LB_GETTOPINDEX, 0, 0);
    // save item data
    lDat = SendMessage(hListBox, LB_GETITEMDATA, (WPARAM) lIndex, 0);
    // delete specified item
    SendMessage(hListBox, LB_DELETESTRING, (WPARAM) lIndex, 0);
    // insert new at this place
    SendMessage(hListBox, LB_INSERTSTRING, (WPARAM) lIndex, (LPARAM) lpString);
    // restore item data
    SendMessage(hListBox, LB_SETITEMDATA, (WPARAM) lIndex, (LPARAM) lDat);
    // restore top index
    SendMessage(hListBox, LB_SETTOPINDEX, (WPARAM) lTop, 0);
    // restore selection
    SendMessage(hListBox, LB_SETCURSEL, (WPARAM) lSel, 0);
    // enable window redraw
    SendMessage(hListBox, WM_SETREDRAW, (WPARAM) TRUE, 0);
    // drop any pending redraw messages
    RedrawWindow(hListBox, NULL, NULL, RDW_VALIDATE | RDW_NOERASE | RDW_NOFRAME | RDW_NOINTERNALPAINT | RDW_UPDATENOW | RDW_ALLCHILDREN);
    // redraw client area of window without erasing background to prevent flickering
    RedrawWindow(hListBox, NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
  }
}

2021.12.28


[ Код ]