Custom controls custom functions
So in my program I have a load of buttons that are really similar, all have the same variables and perform the same functions... So I thought I'd make a "CustomButton" class, a child of C++'s button, but with my functions and all that already in it. The problem is when I have the class
public ref class CustomButton : public System::Windows::Forms::Button{
protected:
virtual void OnMouseDown(System::Windows::Forms::MouseEventArgs ^e) override{
if(e->Button == System::Windows::Forms::MouseButtons::Left) this->Location = System::Drawing::Point(this->Location.X+1, this->Location.Y+1);
开发者_如何学C }
virtual void OnMouseUp(System::Windows::Forms::MouseEventArgs ^e) override{
if(e->Button == System::Windows::Forms::MouseButtons::Left) this->Location = System::Drawing::Point(this->Location.X-1, this->Location.Y-1);
}
};
all set out like above, I can change the variables fine, but when I try and change its functions... It just stops performing other functions at all. I mean, later on when I do this...
CustomButton ^encButton;
this->encButton->Click += gcnew System::EventHandler(this, &Form1::encButton_Click);
It just ignores it completely, won't call the encButton_Click function at all. Same if I try and make it mousedown / whatever.
I figure I'm overwriting something it doesn't like me doing... But I can't think of another way of going about doing what I'm trying to do?
You have to call the base class method to keep the original framework code working. Fix:
virtual void OnMouseDown(System::Windows::Forms::MouseEventArgs ^e) override {
__super::OnMouseDown(e);
if (e->Button == System::Windows::Forms::MouseButtons::Left) {
this->Location = System::Drawing::Point(this->Location.X+1, this->Location.Y+1);
}
}
You've got a choice between calling the base class method first or last. While last is usually the right way, you are changing the button's state enough to warrant call the base class method first. It depends.
精彩评论