Is there any way to find out which TButtonGroup button was pressed?

My application uses the TButtonGroup element. I assign an event handler to each button: doClick. By assigning information to each button ( Pointer (i) ), I can determine which button was called. This is the code:

 procedure TVector_Menu.Synchronize (rows, cols: Int32); var btn: TGrpButtonItem; i: Int32; begin ButtonGroup.Items.Clear; Self.Rows := rows; Self.Cols := cols; for i := 0 to rows * cols - 1 do begin btn := Buttongroup.Items.Add; btn.Data := Pointer (i); btn.ImageIndex := i; btn.OnClick := doClick; end; // for Self.ClientHeight := 4 + rows * ButtonGroup.ButtonHeight; Self.ClientWidth := 22 + cols * ButtonGroup.ButtonWidth; end; // Synchronize // procedure TVector_Menu.doClick (Sender: TObject); var btn: TGrpButtonItem; i, r, c: Int32; begin btn := (Sender as TGrpButtonItem); // @@@ TButtonGroup i := Int32 (btn.Data); get_rc (i, r, c); if Assigned (FOnClick) then FOnClick (Sender, @FButton_Matrix [r, c]); end; // doClick // 

When doClick is called, I get an Invalid Typecast in the line labeled "@@@". The type tag is correct when I use TButtonGroup for btn as well as in typecast, but this one does not contain data properties, and that would be useless.

As a test, I assigned the OnClick event handler to the TButtonGroup control, and I noticed that when I click the button, the button's event handler is called first, and then the TButtonGroup containing the button, the event handler.

Question: is there any way to find out which button from TButtonGroup was pressed?

Using Delphi XE on Windows 7/64

+4
source share
1 answer

You get an invalid type exception because Sender is actually TButtonGroup and not TGrpButtonItem . This means that you need to use a different event handler for each button if you intend to use TGrpButtonItem.OnClick .

In your situation, it is clear that you should use the TButtonGroup.OnButtonClicked event, which provides the button index.

There is a potential trap here, however you need to make sure that you are avoiding. The documentation states:

Occurs when a button is clicked if the OnClick event is missing.

In other words, the OnButtonClicked event will fire only if you have not assigned an OnClick event OnClick to the button group or button element.

+7
source

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


All Articles