How to detect click on CheckBox in TListView

Therefore, when the user clicks on this checkbox, I want to add this item to my list, I tried to use the OnChange event, but this does not work for me, because it fires even if 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 run ONLY when I click on a list item in a ListView

+5
source share
2 answers

In Delphi 2009 and later, you can use the TListView.OnItemChecked event to detect checkboxes. There is no such event in Delphi 2007, in which case you will need to manually detect the notification in your own code. I will demonstrate using the 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; 
+7
source

Since OnItemChecked does not exist, you cannot fire your event only if the item is checked, but you can filter your event as follows

 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 do not have Delphi 2007, but I checked the documentation and should work.

+3
source

Source: https://habr.com/ru/post/1270889/


All Articles