本主题描述了由 System.Windows.Forms.Control 提供的主键盘和鼠标事件。处理事件时,控件作者应该重写受保护的 OnEventName 方法,而不是向事件附加委托。若要查看事件,请参见从组件引发事件。
注意 |
|---|
| 如果没有与事件关联的数据,则会将基类 EventArgs 的一个实例作为参数传递给 OnEventName 方法。 |
键盘事件
您的控件可以处理的常见键盘事件包括 KeyDown、KeyPress 和 KeyUp。
|
事件名称
|
要重写的方法
|
事件说明
|
| KeyDown | void OnKeyDown(KeyEventArgs) | 仅在开始按下键时引发。 |
| KeyPress | void OnKeyPress (KeyPressEventArgs) | 每次按键时引发。如果一直按住某个键,则按操作系统定义的重复速率引发 KeyPress 事件。 |
| KeyUp | void OnKeyUp(KeyEventArgs) | 释放键时引发。 |
鼠标事件
您的控件可以处理的鼠标事件包括 MouseDown、MouseEnter、MouseHover、MouseLeave、MouseMove 和 MouseUp。
|
事件名称
|
要重写的方法
|
事件说明
|
| MouseDown | void OnMouseDown(MouseEventArgs) | 指针位于控件上时,按下鼠标按钮会引发该事件。 |
| MouseEnter | void OnMouseEnter(EventArgs) | 当指针首次进入控件区域时引发。 |
| MouseHover | void OnMouseHover(EventArgs) | 当指针悬停于控件上时引发。 |
| MouseLeave | void OnMouseLeave(EventArgs) | 当指针离开控件区域时引发。 |
| MouseMove | void OnMouseMove(MouseEventArgs) | 当指针在控件区域中移动时引发。 |
| MouseUp | void OnMouseUp(MouseEventArgs) | 指针位于控件上或指针离开控件区域时,松开鼠标按钮会引发该事件。 |
下面的代码片段演示了重写 MouseDown 事件的例子。
Protected Overrides Sub OnMouseDown(ByVal e As MouseEventArgs)
MyBase.OnMouseDown(e)
If Not (myAllowUserEdit) Then
Return
End If
Capture = True
dragging = True
SetDragValue(New Point(e.X, e.Y))
End Sub
protected override void OnMouseDown(MouseEventArgs e) {
base.OnMouseDown(e);
if (!allowUserEdit) {
return;
}
Capture = true;
dragging = true;
SetDragValue(new Point(e.X, e.Y));
}
下面的代码片段演示了重写 MouseMove 事件的例子。
Protected Overrides Sub OnMouseMove(ByVal e As MouseEventArgs)
MyBase.OnMouseMove(e)
If (Not myAllowUserEdit Or Not dragging) Then
Return
End If
SetDragValue(New Point(e.X, e.Y))
End Sub
protected override void OnMouseMove(MouseEventArgs e) {
base.OnMouseMove(e);
if (!allowUserEdit || !dragging) {
return;
}
SetDragValue(new Point(e.X, e.Y));
}
下面的代码片段演示了重写 MouseUp 事件的例子。
Protected Overrides Sub OnMouseUp(ByVal e As MouseEventArgs)
MyBase.OnMouseUp(e)
If (Not myAllowUserEdit Or Not dragging) Then
Return
End If
Capture = False
dragging = False
Value = dragValue
OnValueChanged(EventArgs.Empty)
End Sub
protected override void OnMouseUp(MouseEventArgs e) {
base.OnMouseUp(e);
if (!allowUserEdit || !dragging) {
return;
}
Capture = false;
dragging = false;
value = dragValue;
OnValueChanged(EventArgs.Empty);
}
有关 FlashTrackBar 示例的完整源代码,请参见如何:创建显示进度的 Windows 窗体控件。
请参见