Clipboard GetClipboard GlobalLock fail.

dhkim 1 Reputation point
2021-10-28T07:17:27.53+00:00

The issue is that pGlobal returns nullptr and GetlastError is 6.

if (::OpenClipboard(hWndNewOnwer))
{
HANDLE hGlobal = ::GetClipboardData(CF_UNICODETEXT);

if (hGlobal)
{
BYTE* pGlobal = (BYTE*)GlobalLock(hGlobal);
if (pGlobal != nullptr)
{
Get Clipboard Text Memory....
}
}
}

The issue is that pGlobal returns nullptr and GetlastError is 6 (The handle is invalid.)

In general, it works fine, but GlobalLock on the handle fails only after the SetClipboardData API is called.

Step 1 : SetClipboardData(CF_UNICODETEXT, hMem) ;
Step 2 : OnClipboardUpdate
Step 3: GetClipboardData() -> GlobalLock Fail :GetLastError(6)

When calling SetClipboardData, it only fails when a handle is specified in the OpenClipboard() argument.

I want to know why GlobalLock fails.

SetClipboardData Example

if (::OpenClipboardEx(m_hViewer))
{
::EmptyClipboard();
::SetClipboardData(nFormat, hClipbd) != nullptr)
::CloseClipboard();
}

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,520 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 81,461 Reputation points
    2021-10-28T09:13:20.287+00:00

    This test works for me in a C++/Win32 app :

    TCHAR wsText[255] = TEXT("This is a test");
    int nTextLength = (lstrlen(wsText) + 1) * sizeof(TCHAR);
    HANDLE hClipboardData;
    LPTSTR pClipboardData;
    if (OpenClipboard(hWnd))
    {
        hClipboardData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, nTextLength);
        if (hClipboardData)
        {
            pClipboardData = (LPTSTR)GlobalLock(hClipboardData);
            CopyMemory(pClipboardData, wsText, nTextLength);
            GlobalUnlock(hClipboardData);                           
            EmptyClipboard();
            SetClipboardData(CF_UNICODETEXT, hClipboardData);
        }
        CloseClipboard();
    }
    if (OpenClipboard(hWnd))
    {
        HANDLE hGlobal = GetClipboardData(CF_UNICODETEXT);
        LPTSTR pszData;
        TCHAR wsBuffer[255];
        if (hGlobal != NULL)
        {
            pszData = (LPTSTR)GlobalLock(hGlobal);
            if (NULL != pszData)
            {
                lstrcpy(wsBuffer, pszData);
                GlobalUnlock(hGlobal);
                // ...
            }
        }                       
        CloseClipboard();
    }