Search code examples
c#eventsclipboard

How do I monitor clipboard changes in C#?


Is there a clipboard changed or updated event that i can access through C#?


Solution

  • I think you'll have to use some p/invoke:

    [DllImport("User32.dll", CharSet=CharSet.Auto)]
    public static extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer);
    

    See this article on how to set up a clipboard monitor in c#

    Basically you register your app as a clipboard viewer using

    _ClipboardViewerNext = SetClipboardViewer(this.Handle);
    

    and then you will recieve the WM_DRAWCLIPBOARD message, which you can handle by overriding WndProc:

    protected override void WndProc(ref Message m)
    {
        switch ((Win32.Msgs)m.Msg)
        {
            case Win32.Msgs.WM_DRAWCLIPBOARD:
            // Handle clipboard changed
            break;
            // ... 
       }
    }
    

    (There's more to be done; passing things along the clipboard chain and unregistering your view, but you can get that from the article)