3

Say we had something like

Private Sub ClickObject(ByVal sender As System.Object, ByVal e as System.Eventargs) 
Handles Object1.click, Object2.click, Object3.click

Which takes the event after the 'Handles' and sends them to the function.

Is there an equivalent for this in Delphi, and how would I do it?

RRUZ
  • 134,889
  • 20
  • 356
  • 483
Skeela87
  • 701
  • 6
  • 12
  • 17

2 Answers2

4

Add a TActionList to your form. Add a TAction to it and handle its OnExecute event as you would the OnClick event of some other control. Assign the Action properties of the controls to refer to the action you added to the action list. (This also causes the controls to acquire their captions and enabled and visible properties from the associated action. It's meant to make it easier to have menus and toolbar buttons have uniform states when they represent the same command.)

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
3

Yes.

You can create an event handler and assign it to multiple controls.

procedure TForm1.ThreeControlsClick(Sender: TObject);
begin
  if Sender = Button1 then
    HandleButton1Click
  else if Sender = ComboBox1 then
    HandleComboBox1Click
  else if Sender = Edit1 then
    HandleEdit1Click;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Button1.OnClick := ThreeControlClick;
  ComboBox1.OnClick := ThreeControlClick;
  Edit1.OnClick := ThreeControlClick;
end;
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • You can also use the `Tag` property to differentiate between the different controls. `case (Sender as TComponent).Tag of ...` – Rob Kennedy Apr 10 '11 at 04:35
  • UPDATE: Got it to work. Did have to do a bit of research on it. For where you had Object.Onclick := Function. The function had to be "@Function" with the @. – Skeela87 Apr 10 '11 at 05:03
  • @Hayden: What version of Delphi are you using? The @ shouldn't have been necessary with any recent version. – Ken White Apr 10 '11 at 05:15
  • You shouldn't have needed that, Hayden. Is "Function" really a method belonging to an object? It should be. Standalone functions are not compatible with event handlers. Using the "@" operator can turn a typed pointer into an untyped pointer, and untyped pointers can be assigned to just about any other pointer-like type, even if they're not really compatible. Turn on the "typed @ operator" compiler option and see whether your code still works. – Rob Kennedy Apr 10 '11 at 05:18
  • I am using Lazarus, I'm not what version it uses. The @ quickly fixed it. I'm not an expert on delphi so this was a quick fix for me. However I will look into Your solutions to try learn something new. Thank you =). – Skeela87 Apr 10 '11 at 06:29