How do I scroll over items in a panel

2019-08-20 05:09发布

问题:

I'm creating a winforms app in vb.net and I have a panel with some labels in it. The labels go past the bottom of the panel so the panel shows a vertical scroll bar automatically (which is what I want). However, whenever I scroll the panel down using the mouse wheel, it stops scrolling when one of the labels scrolls up under the mouse. It's like the focus has changed from the panel to the label and the label doesn't need to scroll. I want to just scroll the whole panel using the mouse wheel no matter what comes under the mouse.

回答1:

A Panel control can't have focus and is not selectable. It's just a container.

You can make a custom control derived from Panel and enable it to receive the focus.
This helps a lot in this situation, because this allows to scroll the custom Panel without any other logic behind.
Even if another control, which usually can get the focus - like a TextBox - gets in the way.

This implementation modifies a Panel control Style (ControlStyles.Selectable) to enable it to accept the Focus (the TabStop property is also set to True).

OnMouseDown is also overidden, so that, if a control inside the Panel steals the Focus, you just need to click on the Panel to move the focus on it and then scroll it.

Class PanelWithFocus
    Inherits System.Windows.Forms.Panel

    Public Sub New()
        Me.SetStyle(ControlStyles.Selectable, True)
        InitializeComponent()
    End Sub

    Protected Overrides Sub OnEnter(e As EventArgs)
        MyBase.OnEnter(e)
        Me.Focus()
    End Sub

    Protected Overrides Sub OnMouseDown(e As MouseEventArgs)
        Me.Focus()
        MyBase.OnMouseDown(e)
    End Sub

    Protected Sub InitializeComponent()
        Me.AutoScroll = True
        Me.BorderStyle = BorderStyle.None
        Me.TabStop = True
    End Sub
End Class

To insert this custom control in a Form, locate it in the ToolBox (at the top of it, look for a control named PanelWithFocus) and drop it on the Form.

If you want to substitute an existing Panel with this one, open your Form.Designer and change Me.Panel1 = New System.Windows.Forms.Panel() with Me.Panel1 = New PanelWithFocus().

The same for Friend WithEvents Panel1 As Panel which becomes Friend WithEvents Panel1 As PanelWithFocus



回答2:

Create New Panel User Control

  Public Class PanelX
   Inherits Panel

    Public Sub New()
       Me.AutoScroll = True
    End Sub

   Protected Overrides Sub OnMouseEnter(e As System.EventArgs)
      Me.Select()
      MyBase.OnMouseEnter(e)
   End Sub
  End Class


回答3:

tried this one working fine to me

    Public Sub New()
    ' This call is required by the designer.
    InitializeComponent()
    ' Add any initialization after the InitializeComponent() call.
    AddHandler MouseWheel, AddressOf Panel1_MouseWheel
   End Sub



Private Sub Panel1_MouseWheel(sender As Object, e As MouseEventArgs) Handles Panel1.MouseWheel
    Panel1.Focus()
End Sub