How to paste text in textbox current cursor?

前端 未结 9 801
灰色年华
灰色年华 2020-12-30 19:23

How do you paste text into a TextBox at the current cursor position in Windows Forms?

Not textbox1 += string

相关标签:
9条回答
  • 2020-12-30 19:30
    var insertText = "Text";
    var selectionIndex = textBox1.SelectionStart;
    textBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);
    textBox1.SelectionStart = selectionIndex + insertText.Length;
    
    0 讨论(0)
  • 2020-12-30 19:33
     textBox1.Text = textBox1.Text.Insert(textBox1.SelectionStart, "Whatever");
    
    0 讨论(0)
  • 2020-12-30 19:33

    I know this is late but the most efficient way appears to be:

    textBox1.SelectedText = "Text";
    
    0 讨论(0)
  • 2020-12-30 19:34

    A much easier way would be to use the Paste method:

      textbox1.Paste("text to insert");
    

    I've done this using .NET 4.0

    0 讨论(0)
  • 2020-12-30 19:34

    The simple way would be

    textBox1.Paste();
    

    That replaces the current selection with the contents of the clipboard.

    If you need to do it manually then it's a bit more work. Remember if you're "pasting" then you are "replacing" the current selection if there is one. So you need to handle that first. You'll need to save SelectionStart if you had a selection as removing the text will screw it up.

    string newText = "your text";
    
    int start = textBox1.SelectionStart;
    
    bool haveSelection = textBox1.SelectionLength > 0;
    
    string text = (haveSelection) ? textBox1.Text.Remove(start,textBox1.SelectionLength) : textBox1.Text;
    
    textBox1.Text = text.Insert(start,newText);
    
    if(haveSelection)
    {
        textBox1.SelectionStart = start;
        textBox1.SelectionLength = newText.Length;
    }
    

    After you're done you'll want to invalidate the control to force it to redraw.

    textBox1.Invalidate();
    
    0 讨论(0)
  • 2020-12-30 19:37

    This ensures that the cursor is at some position within the textbox, then inserts the text wherever the cursor is located.

            if (textBox1.CaretIndex <= 0)
            {
    
                   textBox1.Focus();
         textBox1.Text = textBox1.Text.Insert(
                    textBox1.CaretIndex, "Whatever");
            }
            else
            {
                textBox1.Text = textBox1.Text.Insert(
                    textBox1.CaretIndex, "Whatever");
            }
    
    0 讨论(0)
提交回复
热议问题