忽略在继承的RichTextbox上选择文本?

时间:2013-07-05 22:10:48

标签: .net vb.net winforms richtextbox override

在我的usercontrol中我想阻止用户选择文本,我的意思是我要取消(忽略)所有鼠标事件,我已经覆盖了重要事件但似乎没有做任何事情因为我仍然能够选择控件上的文本。

PS:我不能选择禁用控件以防止选择,我想禁用选择。

Public Class RichTextLabel : Inherits RichTextBox

    Private Declare Function HideCaret Lib "user32" (ByVal hwnd As IntPtr) As Integer

    Public Sub New()
        Me.TabStop = False
        Me.Cursor = Cursors.Default
        Me.Size = New Point(200, 20)
        Me.ReadOnly = True
        Me.BorderStyle = BorderStyle.None
        Me.ScrollBars = RichTextBoxScrollBars.None
    End Sub

    Public Sub Add_Colored_Text(ByVal text As String, _
                                ByVal color As Color, _
                                Optional ByVal font As Font = Nothing)

        Dim index As Int32 = Me.TextLength
        Me.AppendText(text)
        Me.SelectionStart = index
        Me.SelectionLength = Me.TextLength - index
        Me.SelectionColor = color
        If font IsNot Nothing Then Me.SelectionFont = font
        Me.SelectionLength = 0

    End Sub

#Region " Overrided Events "

    Protected Overrides Sub OnClick(ByVal e As EventArgs)
        HideCaret(Me.Handle)
        Return
    End Sub

    Protected Overrides Sub OnSelectionChanged(ByVal e As EventArgs)
        HideCaret(Me.Handle)
        Return
    End Sub

    Protected Overrides Sub OnMouseClick(ByVal e As MouseEventArgs)
        HideCaret(Me.Handle)
        ' MyBase.OnClick(e)
        Return
    End Sub

    Protected Overrides Sub OnMouseDoubleClick(ByVal e As MouseEventArgs)
        HideCaret(Me.Handle)
        Return
    End Sub

    Protected Overrides Sub OnMouseDown(ByVal e As MouseEventArgs)
        HideCaret(Me.Handle)
        Return
    End Sub

    Protected Overrides Sub OnMouseUp(ByVal e As MouseEventArgs)
        HideCaret(Me.Handle)
        Return
    End Sub

#End Region

#Region " Handled Events "

    Private Sub On_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Me.MouseHover
        HideCaret(Me.Handle)
    End Sub

    Private Sub On_TextChanged(sender As Object, e As EventArgs) Handles Me.TextChanged
        HideCaret(Me.Handle)
    End Sub

#End Region

End Class

1 个答案:

答案 0 :(得分:1)

有点黑客,但至少它是一个干净的:

  • 向可以有焦点的类添加元素
  • 拥有HideSelection = True(默认设置为True,但请注意不要更改)
  • 覆盖OnEnter事件以将焦点传递给子控件

这样,RichTextBox永远不会占据焦点,所以即使它确实有选定的文本,它也不会显示给用户。


Public Class RichTextLabel : Inherits RichTextBox

    Private controlToTakeFocus As New Label() With {
        .Width = 0,
        .Height = 0,
        .Text = String.Empty}

    Public Sub New()
        ' Default value is True, but is required for this solution
        'Me.HideSelection = True
    End Sub

    Protected Overrides Sub OnMouseDown(e As MouseEventArgs)
        Me.Parent.Controls.Add(controlToTakeFocus)
        controlToTakeFocus.Focus()
    End Sub

End Class

修改:控件controlToTakeFocus需要能够获得焦点,直到Form为止。我将重写的事件更改为OnMouseDown并添加了一行以将控件添加到RichTextLabel的父级,然后尝试将其设置为焦点。可能有一个更好的地方,但这只是为了让它运作。