0

How to add (via code) one or more Buttons in a WinForm TextBox or RichTextBox? Specifically, I want to add buttons at the end of each text line, before the VbCrLf character.

1 Answer 1

3

It will be something like this:

Friend WithEvents Button1 As Button
    Private Sub RichTextBox1_Click(sender As Object, e As EventArgs) Handles RichTextBox1.Click
        Button1 = New Button ' Create new instance
        Me.Button1.Size = New System.Drawing.Size(75, 23) ' give the button a size
        Button1.Text = "My button" ' set the button text
        Me.Button1.UseVisualStyleBackColor = True ' make it look windows like


        Dim pos As Point = RichTextBox1.GetPositionFromCharIndex(RichTextBox1.SelectionStart)  'determine the button position
        RichTextBox1.Controls.Add(Button1) ' get it inside the rich text box
        Button1.Location = New Point(RichTextBox1.Right - Button1.Width, pos.Y + RichTextBox1.Top) ' set the button position
    End Sub

Of course it does not need to be in the Click event, you perhaps may use the KeyPress event to determine if the user pressed enter and then insert it at that point. Also play with the position (POS variable) to change the button position.

Nandostyle

Sign up to request clarification or add additional context in comments.

1 Comment

thanks. but how to scroll down the richtextbox content AND MyButton? (of course, I can implement this based of text height and to re-draw the button in the next position, but it isn't an easier way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.