ScrollBar.Scroll 事件

定義

發生於捲動方塊已經由滑鼠或鍵盤動作移動時。

C#
public event System.Windows.Forms.ScrollEventHandler Scroll;
C#
public event System.Windows.Forms.ScrollEventHandler? Scroll;

事件類型

範例

下列範例會在圖片方塊中捲動影像。 它會使用 Value 捲軸的 ,在使用者捲動時重新繪製影像的新部分。 此程式碼範例是類別概觀所提供較大範例的 ScrollBar 一部分。

注意

如需如何在 Visual Studio 中執行此範例的指示,請參閱如何:使用 Visual Studio 編譯和執行完整Windows Forms程式碼範例

C#
private void HandleScroll(Object sender, ScrollEventArgs e)
{
    //Create a graphics object and draw a portion of the image in the PictureBox.
    Graphics g = pictureBox1.CreateGraphics();

    int xWidth = pictureBox1.Width;
    int yHeight = pictureBox1.Height;

    int x;
    int y;

    if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
    {
        x = e.NewValue;
        y = vScrollBar1.Value;
    }
    else //e.ScrollOrientation == ScrollOrientation.VerticalScroll
    {
        y = e.NewValue;
        x = hScrollBar1.Value;
    }

    g.DrawImage(pictureBox1.Image,
      new Rectangle(0, 0, xWidth, yHeight),  //where to draw the image
      new Rectangle(x, y, xWidth, yHeight),  //the portion of the image to draw
      GraphicsUnit.Pixel);

    pictureBox1.Update();
}

下列程式碼範例使用衍生類別 VScrollBar 。 會建立 和 ValueChanged 事件的事件處理常式 Scroll 。 此程式碼假設 Label 已在表單上建立 和 Button ,而且按鈕具有 事件的事件處理常式 Click 。 按一下按鈕時, Value 捲軸的 屬性會在程式碼中調整。 標籤會顯示內容的 Value 目前值,以及變更它的事件。 您會注意到,當按鈕 Click 的事件變更捲動值時,只會 ValueChanged 引發事件。 相反地,當捲軸手動捲動時, Scroll 事件會在事件之後 ValueChanged 立即引發。

C#
private void AddMyScrollEventHandlers()
 {
    // Create and initialize a VScrollBar.
    VScrollBar vScrollBar1 = new VScrollBar();
 
    // Add event handlers for the OnScroll and OnValueChanged events.
    vScrollBar1.Scroll += new ScrollEventHandler(
       this.vScrollBar1_Scroll);
    vScrollBar1.ValueChanged += new EventHandler(
       this.vScrollBar1_ValueChanged); 
 }
 
 // Create the ValueChanged event handler.
 private void vScrollBar1_ValueChanged(Object sender, 
                                       EventArgs e)
 {
     // Display the new value in the label.
     label1.Text = "vScrollBar Value:(OnValueChanged Event) " + vScrollBar1.Value.ToString();
 }
 
 // Create the Scroll event handler.
 private void vScrollBar1_Scroll(Object sender, 
                                 ScrollEventArgs e)
 {
     // Display the new value in the label.
     label1.Text = "VScrollBar Value:(OnScroll Event) " + e.NewValue.ToString();
 }
 
 private void button1_Click(Object sender, 
                           EventArgs e)
 {
    // Add 40 to the Value property if it will not exceed the Maximum value.
    if (vScrollBar1.Value + 40 < vScrollBar1.Maximum)
    {
        vScrollBar1.Value = vScrollBar1.Value + 40;
    }
 }

備註

如需如何處理事件的詳細資訊,請參閱 處理和引發事件

適用於

產品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另請參閱