我有一个RichTextBox,需要找到垂直滚动条的位置。
有没有不使用Pinvoke的方法来实现这个功能?如果没有,使用Pinvoke的方法是什么?
我需要返回一个整数值。
谢谢帮助!
我有一个RichTextBox,需要找到垂直滚动条的位置。
有没有不使用Pinvoke的方法来实现这个功能?如果没有,使用Pinvoke的方法是什么?
我需要返回一个整数值。
谢谢帮助!
我不知道在没有PInvoke的情况下如何实现这一点。您可以使用PInvoke来调用GetScrollPos。
以下是尝试的方法。
步骤1:通过扩展标准RichTextBox创建自定义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
Console.WriteLine(myRichTextBox1.VScrollPos)
需要注意的几点:
如果您的控件当前未显示垂直滚动条,则调用HScrollPos将使您的程序崩溃。有一些明显的方法可以解决这个问题(在检查属性之前检查滚动条是否正在显示,或始终显示垂直滚动条等)。
根据控件(可能还包括窗体)的大小(更不用说控件文本内容的更改),设置VScrollPos可能会导致程序崩溃或无法恢复到保存VScrollPos值时的位置。
我从未使用过这段代码。我认为您的问题很有趣,并进行了一些研究以得出我的答案。
嗯,是的,Jay的解决方案实现了它承诺的功能:改变滚动条的位置。但它没有改变富文本框内容的位置。
这里是我在codeproject.com上找到的解决方案:https://www.codeproject.com/Questions/293542/VB-Net-Custome-RichTextBox-SetScrollPos
Public Class Rtbscrollfix
Inherits RichTextBox
<DllImport("user32.dll")>
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As IntPtr, ByRef lParam As System.Drawing.Point) As Integer
End Function
Private Const WM_USER = &H400
Private Const EM_GETSCROLLPOS = WM_USER + 221
Private Const EM_SETSCROLLPOS = WM_USER + 222
Public Property ScrollY() As Integer
Get
Dim pt As New System.Drawing.Point
SendMessage(Me.Handle, EM_GETSCROLLPOS, 0, pt)
Return pt.Y
End Get
Set(value As Integer)
SendMessage(Me.Handle, EM_SETSCROLLPOS, 0, New System.Drawing.Point(0, value))
End Set
End Property
End Class