The main keyboard and mouse events provided by System.WinForms.Control are listed below., When handling an event, control authors should override the protected On<EventName> method as opposed to attaching a delegate to the event. For a review of events see Events.
Note that if there is no data associated with the event the base class EventArgs is used for "event data", and passed as an argument to the On<EventName> method.
The common keyboard events that your control may need to handle are KeyPress, KeyDown, and KeyUp.
Event Name | Method to Override | Description of Event |
---|---|---|
KeyDown | void OnKeyDown(KeyEventArgs) |
Raised only when a key is initially pressed. |
KeyPress | void OnKeyPress
|
Raised every time a logical key press occurs. If a key is held down, a KeyPress event is raised at the repeat rate defined by the operating system. |
KeyUp | void OnKeyUp(KeyEventArgs) |
Raised only when a key is released. |
The mouse events that your control may want to handle are: MouseDown, MouseEnter, MouseHover, MouseLeave, MouseMove, and MouseUp.
Event Name | Method to Override | Description of Event |
---|---|---|
MouseDown | void OnMouseDown(MouseEventArgs) |
Raised when the mouse is pressed over the control. |
MouseEnter | void OnMouseEnter(EventArgs) |
Raised when the mouse first enters the region of the control. |
MouseHover | void OnMouseHover(EventArgs) |
Raised only when the mouse hovers over the control. |
MouseLeave | void OnMouseLeave(EventArgs) |
Raised when the mouse leaves the region of the control. |
MouseMove | void OnMouseMove(MouseEventArgs) |
Raised when the mouse moves in the region of the control. |
MouseUp | void OnMouseUp(MouseEventArgs) |
Raised when the mouse is released over the control. |
The MouseDown event is overriden in the following code fragment.
[C#] protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (!allowUserEdit) { return; } Capture = true; dragging = true; SetDragValue(new Point(e.X, e.Y)); }
The MouseMove event is overriden in the following code fragment.
[C#] protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (!allowUserEdit || !dragging) { return; } SetDragValue(new Point(e.X, e.Y)); }
The MouseUp event is overriden in the following code fragment.
[C#] protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (!allowUserEdit || !dragging) { return; } Capture = false; dragging = false; value = dragValue; OnValueChanged(EventArgs.Empty); }
The complete source code for the FlashTrackBar sample is in Win Forms Control Sample.