【问题标题】:Paste text to RichTextBox automatically when user selects copy用户选择复制时自动将文本粘贴到 RichTextBox
【发布时间】:2014-10-12 09:27:44
【问题描述】:

我正在开发一个包含RichTextBox 的C# 应用程序。每次用户从其他应用程序(如 Web 浏览器)复制文本时,我想自动将复制的文本粘贴到 RichTextBox。我可以通过这段代码粘贴复制的文本:

if (Clipboard.ContainsText())
     rtb1.Paste();

问题是我不知道用户何时从弹出菜单中单击复制或在其他应用程序中按下Ctrl + C。 有没有办法在没有Timer 每秒检查剪贴板内容的情况下进行检查?

【问题讨论】:

标签: c# richtextbox copy-paste


【解决方案1】:

我找到了我的答案here

为此,我们需要 pinvoke AddClipboardFormatListenerRemoveClipboardFormatListener

/// <summary>
/// Places the given window in the system-maintained clipboard format listener list.
/// </summary>
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AddClipboardFormatListener(IntPtr hwnd);

/// <summary>
/// Removes the given window from the system-maintained clipboard format listener list.
/// </summary>
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool RemoveClipboardFormatListener(IntPtr hwnd);

/// <summary>
/// Sent when the contents of the clipboard have changed.
/// </summary>
private const int WM_CLIPBOARDUPDATE = 0x031D;

然后我们需要通过调用AddClipboardFormatListener 方法将我们的窗口添加到剪贴板格式侦听器列表中,并将我们的窗口句柄作为参数。将以下代码放在主窗口表单构造函数或其任何加载事件中。

AddClipboardFormatListener(this.Handle);    // Add our window to the clipboard's format listener list.

重写 WndProc 方法,以便我们可以捕获 WM_CLIPBOARDUPDATE 何时发送。

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);

    if (m.Msg == WM_CLIPBOARDUPDATE)
    {
        IDataObject iData = Clipboard.GetDataObject();      // Clipboard's data.

        if (iData.GetDataPresent(DataFormats.Text))
        {
            rtb1.Paste();
        }
     }
}

最后确保在关闭表单之前从剪贴板格式侦听器列表中删除主窗口。

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    RemoveClipboardFormatListener(this.Handle);     // Remove our window from the clipboard's format listener list.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多