简体   繁体   中英

How can I cut text from textbox and copy to clipboard?

Let me begin by saying I am a beginner programmer and I know my last code statement is incorrect. I am writing a notepad application and I can't quite figure out how to cut text. I know that when you cut text all you are doing is copying the selected text to the clipboard, and then deleting the selected text. As I said I know the syntax is wrong I'm just trying to show what I'm attempting to do.

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBox1.Text = Clipboard.GetText(); // will paste whatever text is copied to clipboard
        }
        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(textBox1.SelectedText);//copies whatever text is selected in my textbox
        }
        private void clearClipboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.Clear();//clears clipboard
        }
        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(textBox1.SelectedText);
            textBox1.SelectedText == "";//line I know is incorrect
        }

The best way to do this is to just delegate the operation to the TextBox :

Cut
Copy
Paste

That said, if you want to do it manually, the problem with your line of code is that you are using the == operator instead of the = operator. The code you wrote would work, using the correct operator. :)

Note that textBox1.SelectedText = Clipboard.GetText(); would be a more typical "paste" implementation. There's nothing wrong with replacing the entire text box's text if that's really what you mean to do, but it could surprise some users.

The TextBox has its own Cut , Copy and Paste methods. This is exactly why you should read the documentation first. Not surprisingly, the documentation for the TextBox class lists those methods.

In CompactFramework we do not have TextBox.SelectedText.Copy() method, but we can use public static class Clipboard:

TextBox1.SelectAll();
if (TextBox1.SelectionLength > 0)
{
    Clipboard.SetDataObject(TextBox1.SelectedText);
}

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