Rchrd
Rchrd

Reputation: 35

How to autoscroll panel or picturebox in MouseMove event in VB:NET

I'm trying to autoscroll panel with an image using mousemove event simulating a dynamic zoom. I found this example Pan/scroll an image in VB.NET and this Scroll panel based on mouse position in VB.NET but I realized that the user have to click on the image to drag it, so I tried to modify the code but doesn't work This is what I tried:

Private m_PanStartPoint As New Point
    
Private Sub PictureBox2_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox2.MouseMove

    Dim DeltaX As Integer = (m_PanStartPoint.X - e.X)
    Dim DeltaY As Integer = (m_PanStartPoint.Y - e.Y)

    Panel1.AutoScrollPosition = New Point((DeltaX - Panel1.AutoScrollPosition.X), (DeltaY - Panel1.AutoScrollPosition.Y))
End Sub

Private Sub PictureBox2_MouseEnter(sender As Object, e As EventArgs) Handles PictureBox2.MouseEnter
    PictureBox2.SizeMode = PictureBoxSizeMode.AutoSize
    m_PanStartPoint = New Point(MousePosition)
End Sub

Private Sub PictureBox2_MouseLeave(sender As Object, e As EventArgs) Handles PictureBox2.MouseLeave
    PictureBox2.SizeMode = PictureBoxSizeMode.StretchImage
End Sub

I also tried adding the event MouseHover:

Private Sub PictureBox2_MouseHover(sender As Object, e As EventArgs) Handles PictureBox2.MouseHover
    m_PanStartPoint = New Point(MousePosition)
End Sub

if there is a way to do it without a panel, it would be better.

Upvotes: 0

Views: 277

Answers (1)

mjb
mjb

Reputation: 11

'The VB/XAML code below implements left mouse button click+hold scrolling and also works with touch screens. When using this code, put your frame/grid/image within a scrollviewer as shown below:

'XAML

<ScrollViewer x:Name="ScrollViewerObject" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Hidden" ScrollViewer.CanContentScroll="False" PreviewMouseDown="Part_ScrollViewer_PreviewMouseDown" PreviewMouseMove="Part_ScrollViewer_PreviewMouseMove">
            <Frame x:Name="PartViewer" NavigationUIVisibility="Hidden"/>
        </ScrollViewer>

'VB

Dim LastScrollPos As Double = 0
Dim MouseStartPos AS Double = 0

Private Sub ScrollViewerObject_PreviewMouseDown(sender As Object, e As MouseButtonEventArgs)
    Dim position As Point = Mouse.GetPosition(ScrollViewerObject)
    ScrollViewerObject.UpdateLayout()
    LastScrollPos = ScrollViewerObject.ContentVerticalOffset
    MouseStartPos = position.Y
End Sub

Private Sub ScrollViewerObject_PreviewMouseMove(sender As Object, e As MouseEventArgs)
    If Mouse.LeftButton = MouseButtonState.Pressed Then
        Dim position As Point = Mouse.GetPosition(ScrollViewerObject)
        ScrollViewerObject.ScrollToVerticalOffset(LastScrollPos + (position.Y - MouseStartPos))
    End If
End Sub

Upvotes: 1

Related Questions