可以多次调用 CloseClipboard() 函数吗?

Is it okay to call CloseClipboard() function more than once?

根据某些条件,CloseClipBoard() 函数可能会被调用两次。这样可以吗,还是会导致意外错误?

例如..

void Foo ()
{
    if (::IsClipboardFormatAvailable(clipFormat) && OpenClipboard())
    {
        PasteGridText(clipText);
    }   ::CloseClipboard();
}

BOOL PasteGridText (LPCTSTR text)
{
    ResetClipboardFeedback();..

    if (error)
   {
       **CloseClipboard();**
   }

   return TRUE;
}

为了回答您的问题,是的,您可以调用 CloseClipboard() 两次而不会产生任何实际后果。

这是我的测试 运行:

        bool ocb = OpenClipboard(hwnd);

        if(!ocb)
            printf("Failed to open ClipBoard!\n");
        else
            printf("ClipBoard opened!\n");

        bool ccb = CloseClipboard();

        if(!ccb)
            printf("Failed to close ClipBoard! Error: %lu\n", GetLastError());
        else
            printf("Closed the ClipBoard!\n");

        ccb = CloseClipboard();

        if(!ccb)
            printf("Failed to close ClipBoard! Error: %lu\n", GetLastError());
        else
            printf("Closed the ClipBoard!\n");

结果:

ClipBoard opened!
Closed the ClipBoard!
Failed to close ClipBoard! Error: 1418

ERROR_CLIPBOARD_NOT_OPEN
1418 (0x58A)
Thread does not have a clipboard open.

但是,就像您的问题的评论中提到的那样,每次调用 OpenClipboard 时最好只调用一次 CloseClipboard。我建议坚持该约定。