How to paste text from clipboard into selected tex

2019-09-04 08:07发布

I am relatively new to c# but I am currently creating a Windows Form that has an editor window. I'm struggling with the Paste button though as I have 2 textbox fields, one for the title of the note and one for the note itself. I'm wanting to be able to paste from the clipboard into either textbox.

I have tried using if statements based on noteText.Focused and titleText.Focused but obviously this doesn't work as the Paste button becomes focused as soon as you click it.

Any suggestions would be of great help.

1条回答
叛逆
2楼-- · 2019-09-04 08:28

Create a local variable and save last focused textBox in it.

//subscribe both textBoxes with same GotFocus event handler
textBox1.GotFocus += textBox_GotFocus;
textBox2.GotFocus += textBox_GotFocus;

//local variable
TextBox lastSelected;

//GotFocus
private void textBox_GotFocus(object sender, EventArgs e)
{
    //save last Selected textBox
    lastSelected = sender as TextBox;
}

private void button1_Click_1(object sender, EventArgs e)
{
    //on click get value from clipboard
    if(lastSelected != null)
        lastSelected.Text = Clipboard.GetText();
}
查看更多
登录 后发表回答