How to: Create OnEnter Functionality

The .NET Compact Framework does not support the OnEnter and OnLeave methods for controls. However, because the OnMouseMove method is supported, you can use it and the Capture property to determine when the mouse pointer enters or leaves the control.

This example defines a simple custom control, MouseCapture, which is blue when the mouse movements occur inside the control, and light gray when they outside of the control. It determines whether the mouse coordinate is within its ClientRectangle using the OnMouseMove method.

Note that tapping in and out of the control will not change its color. You must drag the mouse, such as for a drag and drop operation.

To create and implement the custom control

  1. Add the MouseCapture custom control to your project.

    public class MouseCapture : Control
        public MouseCapture()
            this.BackColor = Color.LightGray;
        // If the mouse is over the custom control, Capture is true. 
        protected override void OnMouseMove(MouseEventArgs e)
            this.Capture = this.ClientRectangle.Contains(e.X, e.Y);
            if (this.Capture == true)
                this.BackColor = Color.Blue;
                this.BackColor = Color.LightGray;
  2. Create an instance of MouseCapture in the form's constructor or for its Load event.

    // Assumes mc has been delared 
    // for the form as type MouseCapture.
    mc = new MouseCapture();
    mc.Parent = this;
    mc.Bounds = new Rectangle(20, 50, 100, 50);

This example requires references to the following namespaces:

Community Additions