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.
}