Share via


處理使用者輸入

本主題描述 所提供的 System.Windows.Forms.Control 主要鍵盤和滑鼠事件。 處理事件時,控制項作者應覆寫受保護的 OnEventName 方法,而不是將委派附加至事件。 如需檢閱事件,請參閱從元件引發事件

注意

如果沒有與事件相關聯的資料,基類 EventArgs 的實例會當做引數傳遞至 On EventName 方法。

鍵盤事件

控制項可以處理的常見鍵盤事件為 KeyDownKeyPressKeyUp

事件名稱 要覆寫的方法 事件的描述
KeyDown void OnKeyDown(KeyEventArgs) 只在最初按下按鍵時引發。
KeyPress void OnKeyPress

(KeyPressEventArgs)
每次按下按鍵時引發。 如果保留索引鍵, KeyPress 則會以作業系統所定義的重複速度引發事件。
KeyUp void OnKeyUp(KeyEventArgs) 在放開按鍵時引發。

注意

相較於覆寫上表中的事件,處理鍵盤輸入更為複雜,而且已超出本主題的範圍。 如需詳細資訊,請參閱 Windows Forms 中的使用者輸入

滑鼠事件

控制項可以處理的滑鼠事件為 MouseDownMouseEnterMouseHover 、、 MouseLeaveMouseMoveMouseUp

事件名稱 要覆寫的方法 事件的描述
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 override void OnMouseDown(MouseEventArgs e) {
    base.OnMouseDown(e);
    if (!allowUserEdit) {
        return;
    }
    Capture = true;
    dragging = true;
    SetDragValue(new Point(e.X, e.Y));
}
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

下列程式碼片段顯示覆寫 MouseMove 事件的範例。

protected override void OnMouseMove(MouseEventArgs e) {
    base.OnMouseMove(e);
    if (!allowUserEdit || !dragging) {
        return;
    }
    SetDragValue(new Point(e.X, e.Y));
}
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

下列程式碼片段顯示覆寫 MouseUp 事件的範例。

protected override void OnMouseUp(MouseEventArgs e) {
    base.OnMouseUp(e);
    if (!allowUserEdit || !dragging) {
        return;
    }
    Capture = false;
    dragging = false;
    value = dragValue;
    OnValueChanged(EventArgs.Empty);
}
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

如需 FlashTrackBar 的完整原始程式碼,請參閱如何:建立可顯示進度的 Windows Forms 控制項

另請參閱