我正在开发一个必须显示可能大量文本的触摸屏应用程序。我遇到的问题是附加到文本框的默认滚动条太小而无法在触摸屏应用程序中实际使用。我尝试添加一个单独的滚动条控件并使用它来控制文本框的滚动。到目前为止,我只提出了两种方法。
我想出的第一种方法是使用 ScrollToCaret() 子例程。但是我不喜欢这种方法,因为感觉好像应该有更好的方法将滚动条绑定到文本框而不更改文本选择
这是一个例子:
Dim oSelectionStart As Integer = CInt((TextBox1.Text.Length \ (VScrollBar1.Maximum - VScrollBar1.LargeChange - 1)) * VScrollBar1.Value)
If oSelectionStart >= TextBox1.Text.Length - 10 Then
oSelectionStart = TextBox1.Text.Length
End If
If oSelectionStart <= 10 Or VScrollBar1.Value < 2 Then
oSelectionStart = 0
End If
If Not TextBox1.SelectionStart = oSelectionStart Then
TextBox1.SelectionStart = oSelectionStart
TextBox1.ScrollToCaret()
End If
我想出的第二种方法使用 Windows API 调用来设置滚动条位置并获取其当前位置。然而,这种方法也存在一些缺陷。我无法从文本框滚动信息中获得较大的变化值。大多数时候这无关紧要,但是当文本框上的默认滚动条变大时,这意味着我的滚动条无法正确缩放,使我的滚动条具有滚动到文本底部的效果,而只是酒吧的一半。我发现这种方法的另一个问题是文本框的默认滚动条必须可见,以便我能够检索和设置当前的滚动信息。我遇到的最后一个问题是困扰我发现的两种方法的问题。
下面是示例代码:
Private Sub VScrollBar1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs)
Dim minPos As Integer = 0
Dim maxPos As Integer = 0
Dim newPos As Integer = 0
GetScrollRange(TextBox1.Handle, SBS_VERT, minPos, maxPos)
Dim vScrollPerc As Double = ((100 / (VScrollBar1.Maximum - (VScrollBar1.LargeChange - 1))) * VScrollBar1.Value) * 0.01
newPos = CInt(((maxPos - minPos) * vScrollPerc) + minPos)
SetScrollPos(TextBox1.Handle, SBS_VERT, newPos, True)
PostMessageA(TextBox1.Handle, WM_VSCROLL, SB_THUMBPOSITION + &H10000 * newPos, Nothing)
End Sub
'Scrollbar direction
Const SBS_HORZ = 0
Const SBS_VERT = 1
'Windows Messages
Const WM_VSCROLL = &H115
Const WM_HSCROLL = &H114
Const SB_THUMBPOSITION = 4
<Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Sequential)> Private Structure SCROLLINFO
Public cbSize As Integer
Public fMask As Integer
Public nMin As Integer
Public nMax As Integer
Public nPage As Integer
Public nPos As Integer
Public nTrackPos As Integer
End Structure
Private Enum ScrollBarDirection
SB_HORZ = 0
SB_VERT = 1
SB_CTL = 2
SB_BOTH = 3
End Enum
Private Enum ScrollInfoMask
SIF_RANGE = &H1
SIF_PAGE = &H2
SIF_POS = &H4
SIF_DISABLENOSCROLL = &H8
SIF_TRACKPOS = &H10
SIF_ALL = (SIF_RANGE Or SIF_PAGE Or SIF_POS Or SIF_TRACKPOS)
End Enum
Private Declare Function GetScrollPos Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nBar As Integer) As Integer
Private Declare Function SetScrollPos Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nBar As Integer, ByVal nPos As Integer, ByVal bRedraw As Boolean) As Integer
Private Declare Function PostMessageA Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Boolean
Private Declare Function GetScrollRange Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nBar As Integer, ByRef lpMinPos As Integer, ByRef lpMaxPos As Integer) As Integer
Private Declare Function GetScrollInfo Lib "user32" (ByVal hWnd As IntPtr, ByVal fnBar As ScrollBarDirection, ByRef lpsi As SCROLLINFO) As Integer
我知道必须有更好的方法来做到这一点,但到目前为止,我还没有想出任何合适的解决方案来解决我的问题。任何帮助,将不胜感激。