Copy text to Clipboard

浪子不回头ぞ 提交于 2019-12-04 05:03:12

问题


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..)


回答1:


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.




回答2:


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);
}


来源:https://stackoverflow.com/questions/19499728/copy-text-to-clipboard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!