简体   繁体   中英

How can I copy a line from a Richtextbox when I select it?

I am trying to automatically highlight and copy a single line from a rich text box and store it in a variable when I click on any part of the line.

Is this possible?

The Click event and something like the following should help:

private void richTextBox1_Click(object sender, EventArgs e)
{
    int index = richTextBox1.SelectionStart;
    int line = richTextBox1.GetLineFromCharIndex(index);
    string lineText = (richTextBox1.Lines.Length > 0) ? richTextBox1.Lines[line] : "";

    //Debug output for my own testing purposes
    Debug.WriteLine(lineText);
}  

You may want to do something different when the RichTextBox is empty. I just use an empty string.
Here's an example of the output from a simple app: 示例输出
The text show in the output window reflects the order in which I clicked the lines after typing.
However, one caveat to this is that you don't need to click exactly on the line for it to count. For example, clicking in the empty space below the last line registers as clicking the last line, because that's where the cursor ends up. It might not matter a whole lot, but it's something to be aware of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM