Override event handler in C++ Builder
In Codegear C++ Builder, I'm trying to extend the TMemo VCL class to perform some functionality during the OnKeyDown event. I've set up the control and am able to add it to forms and开发者_开发问答 so forth. The problem is that I am unable to capture the OnKeyDown event (or any other event, for that matter).
Here is my class:
class PACKAGE TREMemoFind : public TMemo
{
private:
TFindDialog *FindDialog;
protected:
void __fastcall MemoKeyDown(TObject *Sender, WORD &Key, TShiftState Shift);
public:
__fastcall TREMemoFind(TComponent* Owner);
__published:
};
__fastcall TREMemoFind::TREMemoFind(TComponent* Owner) : TMemo(Owner)
{
ScrollBars = ssVertical;
OnKeyDown = MemoKeyDown;
}
void __fastcall TREMemoFind::MemoKeyDown(TObject *Sender, WORD &Key, TShiftState Shift)
{
ShowMessage("It worked!");
}
So, I guess my question is: how do I set up the classes that I derive from the VCL classes to perform custom functions when a certain event fires?
It is not a good idea for a component to assign a handler to its own event. That prevents outside code from using that same event, or worse overwriting your assignment with ther own so your custom code does not run anymore. Instead, what you should be doing is overriding the virtual KeyDown() method, ie:
class PACKAGE TREMemoFind : public TMemo
{
protected:
virtual void __fastcall KeyDown(WORD &Key, TShiftState Shift);
public:
__fastcall TREMemoFind(TComponent* Owner);
};
__fastcall TREMemoFind::TREMemoFind(TComponent* Owner) : TMemo(Owner)
{
ScrollBars = ssVertical;
}
void __fastcall TREMemoFind::KeyDown(WORD &Key, TShiftState Shift)
{
ShowMessage("It worked!");
TMemo::KeyDown(Key, Shift); // fire public OnKeyDown event
}
精彩评论