复制文字到剪贴板 [英] Copy text to Clipboard

查看:95
本文介绍了复制文字到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有什么想法吗?

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

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

推荐答案

编辑:如果适用于Winforms。 。

Edit: If for Winforms..

将其放置在您的调用函数中:

Place this in your invoke function:

Clipboard.SetText(ActiveControl.Text);

下面由Daniel Abou Chleih提到:如果您必须与控件交互以调用该函数,焦点
将更改为该控件。

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

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

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

这篇关于复制文字到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆