我正在开发 C#/.NET 应用程序。我想在工具栏上创建一个基本上会调用 Ctrl+C(复制到剪贴板)的按钮。我查看了 Clipboard 类,但问题是因为我在表单上有多个文本框,我需要扫描哪个有焦点以及是否/被选中的文本,以便从中选择文本等,所以我认为必须有我“单线”解决方案。
有什么想法吗?
(另外,如何添加所有 3 个:剪切、复制、粘贴到工具栏,在相同条件下 - 主窗体上的多个 tekstboxes..)
请您参考如下方法:
编辑:如果用于 Winforms..
将它放在你的调用函数中:
Clipboard.SetText(ActiveControl.Text);
正如 Daniel Abou Chleih 在下面提到的:如果您必须与控件交互以调用焦点函数 将更改为该控件。这仅在您通过其他方式调用它时才有效。
编辑: 不是单行,而是在最后一个事件的文本框上工作:
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。
