Search code examples
c#clipboard

How to lock the clipboard?


I was wondering if there is anyway to lock and unlock the clipboard from C#. Basically, I'd be writing something into it and I do not want anyone else to write to it before I pick up my stuff.

How can I do this?


Solution

  • The OpenClipboard() API function, followed by EmptyClipboard() locks the clipboard until CloseClipboard is called. You should probably pass a window handle of a window in the target process, but zero works.

    Here's a C# console app that worked for me when I wanted to test that my application gracefully handled a rogue application locking the clipboard.

    class Program
    {
        [DllImport("user32.dll", EntryPoint = "OpenClipboard", SetLastError = true)]
        private static extern bool OpenClipboard(IntPtr hWndNewOwner);
    
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool CloseClipboard();
    
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool EmptyClipboard();
    
        static void Main(string[] args)
        {
            OpenClipboard(new IntPtr(0));
            EmptyClipboard();
            Console.WriteLine("Clipboard locked. Press enter to unlock and exit.");
            Console.ReadLine();
            CloseClipboard();
        }
    }
    

    These declarations came from pinvoke.net.