Alec
Alec

Reputation: 579

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

Upvotes: 6

Views: 4089

Answers (2)

David Heffernan
David Heffernan

Reputation: 612794

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;

Upvotes: 9

Dsm
Dsm

Reputation: 6013

Since OnItemChecked does not exist, you cannot get your event to fire only when the item is checked, but you can filter your event like this

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

       objUser := Item.Data;
       objListOfChangedUsers.Add(objUser);
     end
     else
     begin
       // just in case there are any actions when unchecking
     end;
   end;
end;

I don't have Delphi 2007 but have checked the documentation and it should work.

Upvotes: 3

Related Questions