Continuing on building our custom control...

 

Handling Mouse Movement

 

Lets add some pizzazz to the square – it seems too stale.  When we enter the square, let’s draw a dark rectangle around the outside, and when we leave let’s erase that border.  

 

In order to achieve this, let’s add a private property called MouseIsOver.  When the mouse enters the control, we’ll set this to true, and when the mouse leaves, we’ll set this to false.  In the Paint event, we’ll check if MouseIsOver = true, and paint a rectangle around our square. (I guess that would actually be a square, but who is counting?)

        private bool MouseIsOver {

            get {

                return mouseIsOver;

            }

            set {

                mouseIsOver = value;

            }

               

        }

        protected override void OnMouseEnter(EventArgs e) {

            base.OnMouseEnter (e);

            MouseIsOver = true;

 

        }

        protected override void OnMouseLeave(EventArgs e) {

            base.OnMouseLeave (e);

            MouseIsOver = false;

        }

 

And in OnPaint, add this code at the bottom….

     protected override void OnPaint(PaintEventArgs e) {

            // [Code snipped]  painted all the squares, now paint

         if (MouseIsOver) {

                e.Graphics.DrawRectangle(Pens.Black, 0,0,this.Width-1,this.Height-1);

            }

             }

 

Running this code alone, it doesn’t look like it does much.  The black rectangle sometimes shows up, but most of the time it doesn’t.  What’s happened?  We haven’t told the control that it needs to paint itself again.  The way to do this is to tell the control to “Invalidate” itself.  A simple change to the MouseIsOver function:

       private bool MouseIsOver {

            get {

                return mouseIsOver;

            }

            set {

                mouseIsOver = value;

                Invalidate();

            }

               

        }

And we have a pretty reliable rectangle showing up on MouseEnter which disappears on MouseLeave.  I’ve talked a bit more about the Invalidate vs. Update vs. Refresh functions here.