更新:2007 年 11 月
.NET Compact Framework 不支持控件的 OnEnter 和 OnLeave 方法。但是,由于支持 OnMouseMove 方法,因此可使用该方法和 Capture 属性来确定鼠标指针进入或离开控件的时间。
此示例定义了一个简单的自定义控件 MouseCapture,当在该控件内部移动鼠标时,该控件将变为蓝色;当鼠标移动到它的外面时,将变为浅灰色。该控件使用 OnMouseMove 方法来确定鼠标坐标是否处于 ClientRectangle 范围之内。
请注意,在控件内部和外部点击不会改变其颜色。您必须拖动鼠标来执行诸如拖放的操作。
创建和实现自定义控件
将 MouseCapture 自定义控件添加到项目中。
Public Class MouseCapture Inherits Control Public Sub New() Me.BackColor = Color.LightGray End Sub 'New ' If the mouse is over the control, Capture is true. Protected Overrides Sub OnMouseMove(e As MouseEventArgs) Me.Capture = Me.ClientRectangle.Contains(e.X, e.Y) If Me.Capture Then ' Blue indicates inside the control. Me.BackColor = Color.Blue Else Me.BackColor = Color.LightGray End If End Sub End Class
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; else this.BackColor = Color.LightGray; } }
在窗体构造函数中或者为窗体 Load 的事件创建一个 MouseCapture 实例。
' Assumes mc has been delared ' for the form as type MouseCapture. Dim mc As New MouseCapture() mc.Parent = Me mc.Bounds = New Rectangle(20, 50, 100, 50)
// 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);
编译代码
此示例需要引用下面的命名空间: