Opening and Closing the Clipboard

Only one program can have the clipboard open at any time. The purpose of the OpenClipboard call is to prevent the clipboard contents from changing while a program is using the clipboard. OpenClipboard returns a BOOL value indicating whether the clipboard was successfully opened. It will not be opened if another application failed to close it. During the early stages of programming for the clipboard, you should probably check this value, but the check isn't crucial in a nonpreemptive multitasking environment. If every program politely opens and then closes the clipboard during a single message without giving control to other programs, then you'll never run into the problem of being unable to open the clipboard.

I've already mentioned avoiding the use of SendMessage or PeekMessage while the clipboard is open, but watch out for a more subtle problem involving message boxes: If you can't allocate a global memory segment to copy the contents of the clipboard, then you might want to display a message box. If this message box isn't system modal, however, the user can switch to another application while the message box is displayed. You should either make the message box system modal or close the clipboard before you display the message box.

You can also run into problems if you leave the clipboard open while you display a dialog box. Edit fields in a dialog box use the clipboard for cutting and pasting text.