c++ - Copy text to Clipboard in MFC -


i tried make quick method set clipboard text in mfc, not work.

void copytexttoclipboard( cstring strtext) {     if (openclipboard(getframe()->getsafehwnd()))     {         emptyclipboard() ;           setclipboarddata (cf_text, strtext.getbuffer() ) ;         closeclipboard () ;     } } 

i 'windows breakpoint' error @ 'setclipboarddata'. know might have done wrong?

edit: comment. modfied. fails at: memcopy function.

void copytexttoclipboard( cstring strtext) { if (openclipboard(getframe()->getsafehwnd())) {     hglobal hglbcopy;       lptstr  lptstrcopy;     hglbcopy = globalalloc(gmem_moveable, (strtext.getlength() + 1) * sizeof(tchar));      if (hglbcopy == null)      {          closeclipboard();          return ;      }      memcpy(globallock(hglbcopy), &strtext, strtext.getlength() + 1 * sizeof(tchar));           globalunlock(hglbcopy);       setclipboarddata(cf_text, hglbcopy);      emptyclipboard() ;         setclipboarddata (cf_text, strtext.getbuffer() ) ;     closeclipboard () ;     } } 

edit: using old msdn example.

const char* output = "test"; const size_t len = strlen(output) + 1; hglobal hmem =  globalalloc(gmem_moveable, len); memcpy(globallock(hmem), output, len); globalunlock(hmem); openclipboard(0); emptyclipboard(); setclipboarddata(cf_text, hmem); closeclipboard(); 

from msdn documentation of setclipboarddata(uformat,hmem)

if hmem parameter identifies memory object, object must have been allocated using function gmem_moveable flag

you can this:

     lptstr  lptstrcopy;       hglobal hglbcopy;       unsigned int strsize=strtext.getlength();//get string lenght      hglbcopy = globalalloc(gmem_moveable, (strsize+1) * sizeof(tchar));//allocate memory object gmem_moveable       if (hglbcopy == null)       {            closeclipboard();            //other error handling      }       lptstrcopy = (lptstr)globallock(hglbcopy);       memcpy(lptstrcopy, strtext.getbuffer(), strsize * sizeof(tchar)); //copy text data      lptstrcopy[strsize] = (tchar) 0;//the null terminator      globalunlock(hglbcopy);       emptyclipboard() ;        setclipboarddata (cf_text,hglbcopy);      closeclipboard () ; 

Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -