在VB.NET for WinForms中的已禁用文本框中启用了滚动条

时间:2012-06-03 20:10:17

标签: .net vb.net winforms textbox scroll

即使TextBox设置为

,我也试图允许在Multiline-TextBox中滚动
textbox.Enabled = False

这是不可能的,因为使用已启用 -Command禁用了滚动条。

此处的默认解决方案是设置

textbox.ReadOnly = True
textbox.Enabled = True

但这对我来说并不是真的有用。使用 ReadOnly ,我仍然可以选择TextBox的文本以及将光标放在其中。但由于我在同一表格上有正常(非 Multiline -TextBoxes)和其他控件,我不希望这种情况发生。我希望与所有其他禁用的TextBox具有完全相同的行为。

对于其他所有内容,例如模仿禁用文本框的颜色等等, ReadOnly -Property有一个合法的解决方法,但我找不到任何选择文本和放置光标。

更新

来自here的一些提示我尝试使用WIN32 API,但它没有按预期工作:

Imports System.Windows.Forms
Imports System.Runtime.InteropServices

Public Class TestTextBox
    Inherits TextBox

    Private Class Native
        <DllImport("user32.dll")> _
        Friend Shared Function EnableScrollBar(ByVal hWnd As IntPtr, ByVal wSBflags As UInteger, ByVal wArrows As UInteger) As Boolean
        End Function
        <DllImport("User32.dll")> _
        Friend Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As UInteger, ByVal wparam As Integer, ByVal lparam As Integer) As Integer
        End Function

        Public Const WM_SETREDRAW As Long = &HB
        Public Const ESB_ENABLE_BOTH As UInteger = 0
        Public Const SB_VERT As UInteger = 1
    End Class

    Public Sub Change() 'Gets called by a Button in my example.
        'Native.SendMessage(Me.Handle, Native.WM_SETREDRAW, New IntPtr(0), IntPtr.Zero)
        Native.EnableScrollBar(Me.Handle, Native.SB_VERT, Native.ESB_ENABLE_BOTH)
        'Native.SendMessage(Me.Handle, Native.WM_SETREDRAW, New IntPtr(1), IntPtr.Zero)
        Me.PerformLayout()
    End Sub

End Class

1 个答案:

答案 0 :(得分:2)

我认为这应该有效。 HideCaret确保在文本框是ReadOnly的情况下隐藏了插入符号。其他WM拦截可防止用户使用鼠标或键盘选择任何内容。

Imports System.Runtime.InteropServices

Public Class CustomTextbox
    Inherits System.Windows.Forms.TextBox

    Private Const WM_KEYDOWN = &H100
    Private Const WM_SYSKEYDOWN = &H104
    Private Const WM_MOUSEMOVE = &H200

    <DllImport("user32.dll")> _
    Private Shared Function HideCaret(ByVal hwnd As IntPtr) As Integer
    End Function

    Protected Overrides Sub OnGotFocus(ByVal e As System.EventArgs)
        If Me.ReadOnly Then HideCaret(Me.Handle)
        MyBase.OnGotFocus(e)
    End Sub

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If Me.ReadOnly And (m.Msg = WM_MOUSEMOVE) Or _
                           (m.Msg = WM_KEYDOWN) Or _
                           (m.Msg = WM_SYSKEYDOWN) Then Exit Sub
        MyBase.WndProc(m)
    End Sub
End Class