Valleriani
Valleriani

Reputation: 193

VB.net, Being able to select text in a richtextbox without losing focus?

VB.net .. Currently I have two controls, one richtextbox and a textbox. The RTB is readonly, and also HideSelection is set to false.

The textbox is generic, it allows for input (to send data).


I want to be able to select things in the richtextbox without losing focus in the textbox. There is a client called 'mushclient' that does this, and it works pretty well. The text is still selected, but it doesn't lose the focus on the chatbar to type in.

I don't exactly know however how to prevent 'focus' though. At the moment it breaks flow when you are in game but want to copy something, you'll have to click the textbox again to start typing again. I understand I could setfocus after clicking the RTB, but this feels overall a bit odd. I was wondering if there is a more elegant solution.

Thanks!

Upvotes: 0

Views: 366

Answers (1)

David Wilson
David Wilson

Reputation: 4439

This seems to work well for me. The TextBox does loose focus, but as soon as the Mouse_UP event fires, the selected text is copied to the clipboard and focus is sent back to the text box.

Public Class Form1
    Dim LostFocusControl As Control

    Private Sub RichTextBox1_MouseUp(sender As Object, e As MouseEventArgs) Handles RichTextBox1.MouseUp
        If RichTextBox1.SelectedText.Length > 0 Then
            Clipboard.SetText(RichTextBox1.SelectedText)
        End If
        If Not IsNothing(LostFocusControl) Then
            LostFocusControl.Focus()
        End If
    End Sub

    Private Sub ControlLostFocus(sender As Object, e As EventArgs) Handles TextBox1.LostFocus
        LostFocusControl = Sender
    End Sub
End Class

The code is a bit longer than it could be, but this makes it easier if later on you want to change the control that focus is returned to. To change the control that you want to return focus to, just change the name of the control that the handler is subscribed to e.g

Change

    Private Sub ControlLostFocus(sender As Object, e As EventArgs) Handles TextBox1.LostFocus

To

    Private Sub ControlLostFocus(sender As Object, e As EventArgs) Handles Listbox1.LostFocus

or whatever the name of the control is that you want to return focus to.

Upvotes: 1

Related Questions