Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trapping button events

Status
Not open for further replies.

kinabalu

Programmer
Joined
Sep 21, 2007
Messages
8
Location
MY
Hi everyone.
Hope any one can help me with this problem.
I have several buttons in a form. I would like to create a procedure/function that do something when a particular button is clicked. I know that this can be done using "case" but cant figure out how to do it.

TQ
 
You could maybe stick a number in each button's Tag property and then in the generic onclick event handler (which is assigned to each button's onclick event) write something like:
Code:
  case (Sender as TButton).Tag of
    1: ShowMessage('Button 1 clicked');
    2: ShowMessage('Button 2 clicked');
    3: ShowMessage('Button 3 clicked');
    4: ShowMessage('Button 4 clicked');
  end;

Clive
Runner_1Revised.gif

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"To err is human, but to really foul things up you need a computer." (Paul Ehrlich)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To get the best answers from this forum see: faq102-5096
 
you can do what you're after using RTTI
Code:
[navy][i]// for automatic syntax highlighting see faq102-6487 
[/i][/navy][b]type[/b]
  TButtonEventType = [b]procedure[/b] [b]of[/b] [b]object[/b];

  TForm1 = [b]class[/b](TForm)
  [b]private[/b]
    [b]procedure[/b] ButtonClick(Sender: TObject);  [navy][i]// attach to each TButton on the form[/i][/navy]
  [navy][i]//snip
[/i][/navy]  [b]published[/b]   [navy][i]// these methods must be published
[/i][/navy]    [b]procedure[/b] Button1Event; 
    [b]procedure[/b] Button2Event;
    [b]procedure[/b] NamedButtonEvent;
  [b]end[/b];
  
[b]implementation[/b]

[b]procedure[/b] ButtonClick(Sender: TObject);
[b]var[/b]
  r : TMethod;
  e : TButtonEventType;
[b]begin[/b]
  [navy][i]// do generic button stuff here
[/i][/navy]  r.Data := Pointer(Self);
  r.Code := Self.MethodAddress(TButton(Sender).Name + [teal]'Event'[/teal]);
  e := TButtonEventType(r);
  e;   [navy][i]// call the published method
[/i][/navy][b]end[/b];

You can also use this technique to call published methods that take parameters. Just modify the TButtonEventType declaration to
Code:
TButtonEventType = [b]procedure[/b](AParam1: String; AInt: Integer) [b]of[/b] [b]object[/b];

and change the call to
Code:
  e([teal]'String'[/teal], 1);
 
oops, while I'm sure you wouldn't have noticed, the ButtonClick method should belong to TForm1 ie.
Code:
[b]procedure[/b] TForm1.ButtonClick(Sender: TObject);
 
Tq for all the responses. I will try all the suggestions and see which one is better.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top