Skip to content

Instantly share code, notes, and snippets.

@glombard
Created December 16, 2013 12:34
Show Gist options
  • Save glombard/7986317 to your computer and use it in GitHub Desktop.
Save glombard/7986317 to your computer and use it in GitHub Desktop.
Monitor Clipboard changes in C# using AddClipboardFormatListener / WM_CLIPBOARDUPDATE. See Clipboard class: http://msdn.microsoft.com/en-us/library/system.windows.clipboard(v=vs.110).aspx
// from: http://stackoverflow.com/questions/2226920/how-to-monitor-clipboard-content-changes-in-c
/// <summary>
/// Provides notifications when the contents of the clipboard is updated.
/// </summary>
public sealed class ClipboardNotification
{
/// <summary>
/// Occurs when the contents of the clipboard is updated.
/// </summary>
public static event EventHandler ClipboardUpdate;
private static NotificationForm _form = new NotificationForm();
/// <summary>
/// Raises the <see cref="ClipboardUpdate"/> event.
/// </summary>
/// <param name="e">Event arguments for the event.</param>
private static void OnClipboardUpdate(EventArgs e)
{
var handler = ClipboardUpdate;
if (handler != null)
{
handler(null, e);
}
}
/// <summary>
/// Hidden form to recieve the WM_CLIPBOARDUPDATE message.
/// </summary>
private class NotificationForm : Form
{
public NotificationForm()
{
NativeMethods.SetParent(Handle, NativeMethods.HWND_MESSAGE);
NativeMethods.AddClipboardFormatListener(Handle);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == NativeMethods.WM_CLIPBOARDUPDATE)
{
OnClipboardUpdate(null);
}
base.WndProc(ref m);
}
}
}
internal static class NativeMethods
{
// See http://msdn.microsoft.com/en-us/library/ms649021%28v=vs.85%29.aspx
public const int WM_CLIPBOARDUPDATE = 0x031D;
public static IntPtr HWND_MESSAGE = new IntPtr(-3);
// See http://msdn.microsoft.com/en-us/library/ms632599%28VS.85%29.aspx#message_only
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool AddClipboardFormatListener(IntPtr hwnd);
// See http://msdn.microsoft.com/en-us/library/ms633541%28v=vs.85%29.aspx
// See http://msdn.microsoft.com/en-us/library/ms649033%28VS.85%29.aspx
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
}
@satabol
Copy link

satabol commented Sep 21, 2016

You code helped me. Thank you!

@PardeepkumarHotmail
Copy link

Hi, for me "handler" is always null. Please guide.

Copy link

ghost commented Jun 20, 2018

Thank you so much! It's very easy to use.

@jpcarrascal
Copy link

jpcarrascal commented Dec 19, 2018

Thanks very much. Works like a charm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment