[Gelöst] Kopieren in die Zwischenablage funktioniert bei jedem 2. Aufruf nicht



  • Hallo,

    folgender Code sei gegeben:

    #include <iostream>
    #include <string>
    #include <windows.h>
    
    static inline void copy_to_clipboard(const std::string& text)
    {  // This is buggy (every second call only empties clipboard)
        std::size_t len {text.size() + 1}; // +1 for terminating '\0'
    
        HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len);
        if (!hMem) return;
    
        memcpy(GlobalLock(hMem), text.c_str(), len);
        GlobalUnlock(hMem);
    
        OpenClipboard(nullptr);
        EmptyClipboard();
        SetClipboardData(CF_TEXT, hMem);
        CloseClipboard();
    
        GlobalFree(hMem);
    }
    
    int main()
    {
        for (std::string line; std::getline(std::cin, line); )
        {
            copy_to_clipboard(line);
        }
    }
    

    Nun ist es so, dass jedes zweite Mal die Zwischenablage einfach nur leer ist, ansonsten funktioniert es wie gewollt. Sprich:

    1. Aufruf: OK
    2. Aufruf: Zwischenablage leer
    ...
    

    Ich habe mir schon auf msdn GlobalAlloc etc. durchgelesen, kann daraus aber nicht meinen Fehler ableiten. Das einzige was ich finde ist

    If an application calls OpenClipboard with hwnd set to NULL, EmptyClipboard sets the clipboard owner to NULL; this causes SetClipboardData to fail.

    Ich verstehe das aber ehrlich gesag nicht.

    Kann mir jemand einen Tipp geben, was hier schief läuft und wie man es verhindert? Ach ja, wenn ich das GlobalFree auskommentiere besteht das Problem nicht, aber die "Lösung" kann ich ja nicht akzeptieren!

    vielen Dank im Voraus,
    LG



  • Doch musst du! Denn das ist die Lösung.



  • Agh... kein wunder antwortet niemand so lange (wer lesen kann ist klar im Vorteil)

    If SetClipboardData succeeds, the system owns the object identified by the hMem parameter. The application may not write to or free the data once ownership has been transferred to the system [...]

    Danke.


Anmelden zum Antworten