Copy text to Clipboard

2019-02-28 00:15发布

I am doing C#/.NET app. I want to make a button on toolbar that will basically invoke Ctrl+C (copy to clipboard). I looked to Clipboard class, but problem is since I have multiple textboxes on form, I would need to scan which one has focus and if/is selected text, in order to select text from it etc., so I think there must me “one-liner” solution.

Any ideas?

(Also, how to add all 3: Cut, Copy, Paste to toolbar, under same conditions- multiple tekstboxes on main form..)

标签: c# clipboard
2条回答
爷的心禁止访问
2楼-- · 2019-02-28 00:45

If you are using WinForms I possibly have a small Solution for that problem.

Create an Object to store your last selected TextBox

TextBox lastSelectedTextBox = null;

In your Constructor create an Eventhandler for each TextBox in your Form for the GotFocus-Event by calling the AddGotFocusEventHandler-Method with the parameter this.Controls.

public void AddGotFocusEventHandler(Control.ControlCollection controls)
{
    foreach (Control ctrl in controls)
    {
        if(ctrl is TextBox)
            ctrl.GotFocus += ctrl_GotFocus;

        AddGotFocusEventHandler(ctrl.Controls);
    }
}

And set the lastSelectedTextBox to your currently selected TextBox

void c_GotFocus(object sender, EventArgs e)
{
    TextBox selectedTextBox = (TextBox)sender;
    lastSelectedTextBox = selectedTextBox;
}

In your Click-EventHandler for the button check if selectedText is null and copy the text to clipboard:

private void Button_Click(object sender, EventArgs e)
{
    if(String.IsNullOrWhiteSpace(lastSelectedTextBox.SelectedText))
       Clipboard.SetText(lastSelectedTextBox.Text);
    else
       Clipboard.SetText(lastSelectedTextBox.SelectedText);
}
查看更多
甜甜的少女心
3楼-- · 2019-02-28 00:55

Edit: If for Winforms..

Place this in your invoke function:

Clipboard.SetText(ActiveControl.Text);

As mentioned below by Daniel Abou Chleih: If you have to interact with a control to invoke the function the focus will be changed to that control. This only works if you call it through other means.

Edit: Not a one-liner but works on the last active TextBox:

private Control lastInputControl { get; set; }
protected override void WndProc(ref Message m)
{
    // WM_SETFOCUS fired.
    if (m.Msg == 0x0007)
    {
        if (ActiveControl is TextBox)
        {
            lastInputControl = ActiveControl;
        }
    }

    // Process the message so that ActiveControl might change.
    base.WndProc(ref m);

    if (ActiveControl is TextBox && lastInputControl != ActiveControl)
    {
        lastInputControl = ActiveControl;
    }
}

public void CopyActiveText()
{
        if (lastInputControl == null) return;
        Clipboard.SetText(lastInputControl.Text);
}

Now you can call CopyActiveText() to get the most recent TextBox that lost focus last or currently has focus.

查看更多
登录 后发表回答