[MFC] Cum scriu un text in clipboard?

Despre MFC, ATL si alte biblioteci C++ de la Microsoft (forum moderat)
Post Reply
User avatar
Ovidiu Cucu
Fondator
Fondator
Posts: 3778
Joined: 11 Jul 2007, 16:10
Judet: Iaşi
Location: Iasi
Contact:

[MFC] Cum scriu un text in clipboard?

Post by Ovidiu Cucu » 05 Sep 2010, 18:09

Intrebare: Cum scriu un text in clipboard?

Raspuns: Sunt necesari urmatorii pasi:
  1. se scrie textul intr-un memory shared file, la fel ca in orice alt tip de fisier;
  2. se instantiaza un obiect tip COleDataSource;
  3. se obtine un handle la memoria care contine fisierul;
  4. se apeleaza COleDataSource::CacheGlobalData pasand-ui formatul (CF_TEXT daca textul e ANSI sau CF_UNICODETEXT daca este UNICODE) si handle-ul la memorie;
  5. Se plaseaza continutul pe clipboard cu COleDataSource::SetClipboard.
Exemplu

Code: Select all

#include <afxole.h>
#include <afxadv.h>
//...
BOOL CFoo::CStringToClipboard(const CString& strText)
{
   // NOTE: Call AfxOleInit in IntInstance of the application class!
   BOOL bRet = FALSE;
   try
   {
      // write the text in a shared memory file
      CSharedFile file(GMEM_MOVEABLE|GMEM_DDESHARE|GMEM_ZEROINIT);
      file.Write(strText, strText.GetLength() * sizeof(TCHAR)); 

      // create a new COleDataSource object
      COleDataSource* pOleDataSrc = new COleDataSource;

      // get a handle to the memory block with the contents of the memory file.
      HGLOBAL hDataMem = file.Detach();

      // call CacheGlobalData with format and memory handle 
      CLIPFORMAT cfFormat = CF_TEXT;
#ifdef UNICODE
      cfFormat = CF_UNICODETEXT;
#endif
      pOleDataSrc->CacheGlobalData(cfFormat, hDataMem);

      // place data to the clipboard
      pOleDataSrc->SetClipboard();

      // success
      bRet = TRUE;
   }
   catch(CException* e)
   {
      e->ReportError();
      e->Delete();
   }
   return bRet;
}
Note
  • DLL-urile de OLE trebuiesc initializate printr-un apel la AfxOleInit in functa InitInstance a clasei aplicatiei (derivata din CWinApp).
Vezi si << Back to MFC index



Post Reply