Search code examples
cachingmfccomclipboard

MFC/COM: Preventing clipboard from being cleared once the application is closed


I'm experiencing a problem: The OLE clipboard gets cleared once I close my application that cached global data into it.

Here's what I'm doing:

class CMyOleDataSource sealed:public COleDataSource{
public:
    CMyOleDataSource(){
        // ctor
        // - target may inform if paste succeeded
        DelaySetData( CEditor::cfPasteSucceeded ); // global const value
        // - cache a plain ANSI text
        char text[]="hello world";
        const HANDLE hText=::GlobalAlloc(GMEM_SHARE,::lstrlen(text)+1); // "+1" = null-char
        ::lstrcpy( (LPSTR)::GlobalLock(hText), text );
        ::GlobalUnlock(hText);
        CacheGlobalData( CF_TEXT, hText );
    }
};
...
COleDataSource *ods=new CMyOleDataSource; // instantiation somewhere in the app

Two scenarios of use:

(1) The app caches "hello world", I paste it into NotePad, and close the app - the text remains cached in the clipboard.

(2) The app caches "hello world" and I close the app without pasting it anywhere - the text gets discarded from the clipboard.

Therefore a question - what am I doing wrong? Do I need to yet set anything in the COleDataSource object?

Thanks in advance for any help.


Solution

  • This is a normal behaviour of the OLE clipboard functions. The data is cached in a global context when it is requested for the first time.

    If OLE clipboard data is never requested it just get cleared from the clipboard.

    To prevent this use OleFlushClipboard upon exit of your application. Read the docs of the function fur further information.