HOW TO:建立 OnEnter 功能
更新: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);
編譯程式碼
這個範例需要下列命名空間的參考: