0

I'm developing an C# application which includes a RichTextBox. I want to paste the copied text to RichTextBox automatically, every time user copies a text from other application like web browsers. I can paste the copied text by this code:

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

The problem is I don't know when exactly user clicks on copy from pop up menu or presses Ctrl + C in other applications. Is there any way to check that without having a Timer to check the clipboard content like every second?

Ghasem
  • 14,455
  • 21
  • 138
  • 171
  • 2
    possible duplicate of [How to monitor clipboard content changes in C#?](http://stackoverflow.com/questions/2226920/how-to-monitor-clipboard-content-changes-in-c) also [this post](http://stackoverflow.com/questions/621577/clipboard-event-c-sharp) – TaW Oct 12 '14 at 09:34
  • @TaW you guide me to my answer. thank you – Ghasem Oct 12 '14 at 15:56

1 Answers1

0

I found my answer here.

In order to do that we need to pinvoke the AddClipboardFormatListener and RemoveClipboardFormatListener.

/// <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;

Then we need to add our window to the clipboard format listener list by calling the AddClipboardFormatListener method with our window’s handle as a parameter. Place the following code in your main window form constructor or any of its load events.

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

Override the WndProc method so we can catch when the WM_CLIPBOARDUPDATE is send.

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

And finally make sure to remove your main window from the clipboard format listener list before closing your form.

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