Posts WinForms + Control Inheritance Tip (or at least a Reminder)
Post
Cancel

WinForms + Control Inheritance Tip (or at least a Reminder)

OK, this should be a given, however since it happened to me I guess I'll pass it along ;-)

I created a new Button type control, so I inherited it from a System.Windows.Forms.Button.  Because I'm trying to make the screens look like a previous product, I'm using the same graphics they were using (except in picture boxes) to draw the buttons.  There are two states to the button, pressed and depressed.  So I Override the OnMouseDown and OnMouseUp to change a member variable to let me know the current state.  I also cause an Invalidate so that the control will redraw when it can.  During the OnPaint, it uses the member variable to know what image to use.  Straight forward enough and basic testing showed that it was working.  (Note: Keep in mind that I worked on this control about a month ago.)  Today it was time to use this control within the form I'm working on.  Obviously, since it's a button... when someone Click's it, something is supposed to happen.  My Click event was never firing.  WTF?

After tracing what was going on, I discovered that I missed something.  Whenever you are inheriting from a base component, in this case a Button, and you Override say the OnMouseDown / OnMouseUp events... be sure to call upon the MyBase versions of those methods to allow the base implementation to do it's work as well.  There are times when you may not want the base class to do anything; but in a lot of cases you do.  In this example, the Click event wasn't working because the OnMouseDown and OnMouseUp were not allowing the base implementation to create the Click event since those methods were never being called upon.

I know, probably not a true tip in the sense of the word, but hey... if it saves you some time debugging your code wondering why it's not working as expected; I'd say it's a tip.  At least it counts as a reminder ;-)

This post is licensed under CC BY 4.0 by the author.