CloseClipboard function

The CloseClipboard function closes the clipboard. This function must be called after a successful call to OpenClipboard. It releases the clipboard for other applications to open it.

Syntax

BOOL CloseClipboard(void);

Parameters

This function does not take any parameters.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

  • Only the window that opened the clipboard with OpenClipboard may call CloseClipboard.
  • Applications should not keep the clipboard open for an extended period of time.
  • After calling CloseClipboard, the ownership of the clipboard content is transferred to the system.

Example

The following example opens the clipboard, copies a text string to it, and then closes the clipboard.

#include <windows.h>
#include <stdio.h>

int main(void)
{
    if (!OpenClipboard(NULL)) {
        printf("Could not open clipboard. Error: %lu\\n", GetLastError());
        return 1;
    }

    const char *text = "Hello from CloseClipboard example!";
    HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, strlen(text) + 1);
    if (!hMem) {
        CloseClipboard();
        printf("GlobalAlloc failed.\\n");
        return 1;
    }

    memcpy(GlobalLock(hMem), text, strlen(text) + 1);
    GlobalUnlock(hMem);

    if (!SetClipboardData(CF_TEXT, hMem)) {
        printf("SetClipboardData failed.\\n");
        GlobalFree(hMem);
    }

    if (!CloseClipboard()) {
        printf("CloseClipboard failed. Error: %lu\\n", GetLastError());
    }

    return 0;
}

Related topics