将文本复制到剪贴板

我在做C#/ .NET应用程序。 我想在工具栏上创建一个按钮,它基本上会调用Ctrl + C(复制到剪贴板)。 我看了剪贴板类,但问题是因为我在表单上有多个文本框,我需要扫描哪一个有焦点,如果/是选择文本,以便从中选择文本等,所以我认为必须有我“单线“解决方案。

有任何想法吗?

(另外,如何在相同条件下添加所有3:剪切,复制,粘贴到工具栏 – 主窗体上的多个tekstbox ..)

编辑 :如果是Winforms ..

将它放在你的调用函数中:

 Clipboard.SetText(ActiveControl.Text); 

正如Daniel Abou Chleih所述:如果你必须与控件交互以调用该函数,焦点将被更改为该控件。 这仅在您通过其他方式调用时才有效。

编辑 :不是单行,但适用于最后一个活动的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); } 

现在,您可以调用CopyActiveText()来获取最近失去焦点或当前具有焦点的最新TextBox。

如果你使用WinForms我可能有一个小问题的解决方案。

创建一个Object来存储上次选择的TextBox

 TextBox lastSelectedTextBox = null; 

在构造函数中,通过使用参数this.Controls调用AddGotFocusEventHandler -Method,为Form中的每个TextBoxGotFocus -Event创建一个Eventhandler。

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

并将lastSelectedTextBox设置为当前选定的TextBox

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

在Click-EventHandler中,按钮检查selectedText是否为null并将文本复制到剪贴板:

 private void Button_Click(object sender, EventArgs e) { if(String.IsNullOrWhiteSpace(lastSelectedTextBox.SelectedText)) Clipboard.SetText(lastSelectedTextBox.Text); else Clipboard.SetText(lastSelectedTextBox.SelectedText); }