Loading nodes into a tree view control that expand past the viewable area of the tree view can cause the scroll bars to move and display the content of the control incorrectly as in figure 1.
Figure 1
To control the position of the scrollbars you can use the following code which will result in the tree view displaying properly as in figure 2.
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("user32.dll", CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
Public Shared Function GetScrollPos(ByVal hWnd As Integer, ByVal nBar As Integer) As Integer
End Function
<DllImport("user32.dll")> _
Private Shared Function SetScrollPos(ByVal hWnd As IntPtr, ByVal nBar As Integer, ByVal nPos As Integer, ByVal bRedraw As Boolean) As Integer
End Function
Private Const SB_HORZ As Integer = &H0
Private Const SB_VERT As Integer = &H1
Dim t As Boolean = False
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
If t = False Then
t = True
Me.TreeView1.ExpandAll()
Else
t = False
Me.TreeView1.CollapseAll()
End If
'Dim ScrollPos As Point = GetTreeViewScrollPos(Me.TreeView1)
' Function sets the position of the treeview you pass
Catch ex As Exception
End Try
End Sub
''' <summary>
''' Gets the current position of the scroll
''' </summary>
''' <param name="treeView"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function GetTreeViewScrollPos(ByVal treeView As TreeView) As Point
GetTreeViewScrollPos = New Point(0, 0)
Try
GetTreeViewScrollPos = New Point(GetScrollPos(CInt(treeView.Handle), SB_HORZ), GetScrollPos(CInt(treeView.Handle), SB_VERT))
Catch ex As Exception
End Try
Return GetTreeViewScrollPos
End Function
''' <summary>
''' Sets the position of the scroll of passed treeview control
''' </summary>
''' <param name="treeView"></param>
''' <param name="scrollPosition"></param>
''' <remarks></remarks>
Private Sub SetTreeViewScrollPos(ByRef treeView As TreeView, ByRef scrollPosition As Point)
Try
SetScrollPos(DirectCast(treeView.Handle, IntPtr), SB_HORZ, scrollPosition.X, True)
SetScrollPos(DirectCast(treeView.Handle, IntPtr), SB_VERT, scrollPosition.Y, True)
If treeView.Nodes.Count > 0 Then
Dim currentNode As TreeNode = treeView.Nodes(0) 'treeView.GetNodeAt(0, 0)
currentNode.EnsureVisible()
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SetTreeViewScrollPos(Me.TreeView1, New Point(0, 0))
End Sub
End Class
No comments:
Post a Comment