Search code examples
delphidelphi-2007tlistview

How to detect a click on the CheckBox in the TListView


So basically when a user clicks on the checkbox, I want to add that item in my list, I have tried using the OnChange event but this is not working for me as it gets fired even when the Checkbox is not clicked.

My code is simple and straightforward

procedure LvUserChange(Sender: TObject; Item: TListItem;Change: TItemChange);
 var
 objUser : TUsers;
begin
   if not assigned(objListOfChangedUsers) then
   objListOfChangedUsers := TObjectList.Create;

   objUser := Item.Data;
   objListOfChangedUsers.Add(objUser);
end;

I want this code to be fired ONLY when the checkbox is clicked in the ListView


Solution

  • In Delphi 2009 and later, you can use the TListView.OnItemChecked event to detect checkbox clicks. Delphi 2007 does not have such an event, in which case you will need to detect the notification manually in your own code. I will demonstrate with an interposer class, but there are other ways to do this.

    uses
      ..., CommCtrl, ComCtrls, ...;
    
    type
      TListView = class(ComCtrls.TListView)
      protected
        procedure CNNotify(var Message: TWMNotifyLV); message CN_NOTIFY;
      end;
    
    ....
    
    procedure TListView.CNNotify(var Message: TWMNotifyLV);
    begin
      inherited;
      if Message.NMHdr.code = LVN_ITEMCHANGED then
      begin
        if (Message.NMListView.uChanged = LVIF_STATE) and
           ( ((Message.NMListView.uOldState and LVIS_STATEIMAGEMASK) shr 12)
             <> ((Message.NMListView.uNewState and LVIS_STATEIMAGEMASK) shr 12)) then
        begin
          // changing check box state will land you here
        end;
      end;
    end;