Scrollbar vertical position as integer in vb.net
I have a RichTextBox and I need to find the position of a vertical scrollbar.
Is there a way to do this without Pinvoke? If not, what is the way to do it using Pinvoke?
I need to return an integer value.
Thanks for the help!
I don't know how to do this without PInvoke. You can use PInvoke to call GetScrollPos .
You can try it here.
Step 1: Create your own RichTextBox control by extending the standard RichTextBox.
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Windows.Forms
Namespace WindowsFormsApplication1
Public Class MyRichTextBox
Inherits RichTextBox
<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Public Shared Function GetScrollPos(ByVal hWnd As IntPtr, 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
''' <summary>
''' Gets and Sets the Horizontal Scroll position of the control.
''' </summary>
Public Property HScrollPos() As Integer
Get
Return GetScrollPos(DirectCast(Me.Handle, IntPtr), SB_HORZ)
End Get
Set(ByVal value As Integer)
SetScrollPos(DirectCast(Me.Handle, IntPtr), SB_HORZ, value, True)
End Set
End Property
''' <summary>
''' Gets and Sets the Vertical Scroll position of the control.
''' </summary>
Public Property VScrollPos() As Integer
Get
Return GetScrollPos(DirectCast(Me.Handle, IntPtr), SB_VERT)
End Get
Set(ByVal value As Integer)
SetScrollPos(DirectCast(Me.Handle, IntPtr), SB_VERT, value, True)
End Set
End Property
End Class
End Namespace
This will add two properties to the standard RichTextBox: HScrollPos and VScrollPos. These properties will allow you to get and set the horizontal and vertical position of the scrollbar in your control.
Step 2: Create a test form and try your control.
Create a Winform in the same project as your custom control. Drop the custom control on the test form and add the button to the form. In the Click event form, add the following code to view your own vertical scroll position.
Console.WriteLine(myRichTextBox1.VScrollPos)
A few things to look out for:
-
If your control is not currently displaying a vertical scrollbar, calling HScrollPos will crash your program. There are some obvious ways around this (make sure the property check scrollbar is shown or the vertical scrollbar is always visible, etc.).
-
Depending on how the control (and possibly the form) is sized (do not indicate changes to the content of the control text), setting VScrollPos may cause your program to crash or not recover to the point where the VScrollPos value was saved.
-
I have never used this code. I thought your question was interesting and a bit to answer my question.