Handling User Input and Events

Learning Resources
 

Handling User Input and Events


When handling an event, control authors should override the protected OnEventName method rather than attaching a delegate to the event. For a review of events,

The common keyboard events that your control can handle are KeyDown, KeyPress, 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

(KeyPressEventArgs)

Raised every time a key is pressed. 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 when a key is released.

Note Note

Handling keyboard input is considerably more complex than overriding the events in the preceding table and is beyond the scope of this topic. For more information, see User Input in Windows Forms.

The mouse events that your control can 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 button is pressed while the pointer is over the control.

MouseEnter

void OnMouseEnter(EventArgs)

Raised when the pointer first enters the region of the control.

MouseHover

void OnMouseHover(EventArgs)

Raised when the pointer hovers over the control.

MouseLeave

void OnMouseLeave(EventArgs)

Raised when the pointer leaves the region of the control.

MouseMove

void OnMouseMove(MouseEventArgs)

Raised when the pointer moves in the region of the control.

MouseUp

void OnMouseUp(MouseEventArgs)

Raised when the mouse button is released while the pointer is over the control or the pointer leaves the region of the control.

The following code fragment shows an example of overriding the MouseDown event.

protected override void OnMouseDown(MouseEventArgs e) {
    base.OnMouseDown(e);
    if (!allowUserEdit) {
        return;
    }
    Capture = true;
    dragging = true;
    SetDragValue(new Point(e.X, e.Y));
}

The following code fragment shows an example of overriding the MouseMove event.

An C# example
protected override void OnMouseMove(MouseEventArgs e) {
    base.OnMouseMove(e);
    if (!allowUserEdit || !dragging) {
        return;
    }
    SetDragValue(new Point(e.X, e.Y));
}

The following code fragment shows an example of overriding the MouseUp event.

An C# example
protected override void OnMouseUp(MouseEventArgs e) {
    base.OnMouseUp(e);
    if (!allowUserEdit || !dragging) {
        return;
    }
    Capture = false;
    dragging = false;
    value = dragValue;
    OnValueChanged(EventArgs.Empty);
}

For the complete source code for the FlashTrackBar sampl

--MSDN
 For Support