管理滑鼠指標 (Windows Forms .NET)

滑鼠 指標,有時稱為游標 ,是點陣圖,指定螢幕上的焦點點,以便使用者輸入滑鼠。 本主題提供 Windows Forms 中滑鼠指標的概觀,並說明修改及控制滑鼠指標的一些方式。

重要

.NET 7 和 .NET 6 的桌面指南檔正在建置中。

存取滑鼠指標

滑鼠指標是由 Cursor 類別表示,而且每個 Control 指標都有一個 Control.Cursor 屬性,指定該控制項的指標。 類別 Cursor 包含描述指標的屬性,例如 PositionHotSpot 屬性,以及可以修改指標外觀的方法,例如 ShowHideDrawStretched 方法。

下列範例會在游標位於按鈕上方時隱藏游標:

private void button1_MouseEnter(object sender, EventArgs e) =>
    Cursor.Hide();

private void button1_MouseLeave(object sender, EventArgs e) =>
    Cursor.Show();
Private Sub Button1_MouseEnter(sender As Object, e As EventArgs) Handles Button1.MouseEnter
    Cursor.Hide()
End Sub

Private Sub Button1_MouseLeave(sender As Object, e As EventArgs) Handles Button1.MouseLeave
    Cursor.Show()
End Sub

控制滑鼠指標

有時候,您可能想要限制可以使用滑鼠指標的區域,或變更滑鼠的位置。 您可以使用 的 屬性,取得或設定滑鼠 PositionCursor 目前位置。 此外,您可以限制可以使用滑鼠指標的區域來設定 Clip 屬性。 根據預設,剪輯區域是整個畫面。

下列範例會在按一下滑鼠指標時,將滑鼠指標放在兩個按鈕之間:

private void button1_Click(object sender, EventArgs e) =>
    Cursor.Position = PointToScreen(button2.Location);

private void button2_Click(object sender, EventArgs e) =>
    Cursor.Position = PointToScreen(button1.Location);
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    PointToScreen(Button2.Location)
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    PointToScreen(Button1.Location)
End Sub

變更滑鼠指標

變更滑鼠指標是向使用者提供意見反應的重要方式。 例如,您可以在 和 MouseLeave 事件的處理常式 MouseEnter 中修改滑鼠指標,告知使用者計算發生,並限制控制項中的使用者互動。 有時候,滑鼠指標會因為系統事件而變更,例如當您的應用程式涉及拖放作業時。

變更滑鼠指標的主要方法是將 控制項的 或 屬性設定 Control.Cursor 為新的 CursorDefaultCursor 如需變更滑鼠指標的範例,請參閱 類別中的 Cursor 程式碼範例。 此外,類別 Cursors 會針對許多不同類型的指標公開一組 Cursor 物件,例如類似手部的指標。

下列範例會將按鈕的滑鼠指標游標變更為手部:

button2.Cursor = System.Windows.Forms.Cursors.Hand;
Button2.Cursor = System.Windows.Forms.Cursors.Hand

若要顯示類似沙漏的等候指標,只要滑鼠指標位於 控制項上,請使用 UseWaitCursor 類別的 Control 屬性。

另請參閱