简体   繁体   中英

Cut, Copy, and paste in C#?

I have a lot of textboxes. I have a button that will cut the selected text of the Focused textbox. How do i do that? I have tried this:

        if (((TextBox)(pictureBox1.Controls[0])).SelectionLength > 0)
        {
            ((TextBox)(pictureBox1.Controls[0])).Cut();
        }

Hope it is WinForms

var textboxes = (from textbox in this.Controls.OfType<TextBox>()
                    where textbox.SelectedText != string.Empty
                    select textbox).FirstOrDefault();
if (textboxes != null)
{
    textboxes.Cut();
}

Loop through the controls to find the one with selected text:

foreach (Control x in this.PictureBox1.Controls)
{
    if (x is TextBox)
    {
        if (((TextBox)x).SelectionLength > 0)
        {
            ((TextBox)(x).Cut(); // Or some other method to get the text.
        }
    }
}

Hope this helps!

Try using common Enter and Leave events to set the last TextBox that had Focus.

private void textBox_Enter(object sender, EventArgs e)
{
    focusedTextBox = null;
}

private void textBox_Leave(object sender, EventArgs e)
{
    focusedTextBox = (TextBox)sender;
}

private void button1_Click(object sender, EventArgs e)
{
    if (!(focusedTextBox == null))
    {
        if (focusedTextBox.SelectionLength > 0)
        {
            Clipboard.SetText(focusedTextBox.SelectedText);
            focusedTextBox.SelectedText = "";
            focusedTextBox = null;
        }
    }
}

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