set GLOBAL clipboard text in windows, native c++
I have an ASCII string (A null term开发者_开发问答inated char array) in a console app.
all I want to do is make it so my app will put this string into the "global clipboard" so that after running it, I can ctrl+v in any standard app (in this case, visual studio) and my string will be pasted!
how do I do this?
I have done:
void SetClipboardText(char* txt)
{
if(!OpenClipboard(NULL))
{
__asm int 3;
}
int l = PIstrlen(txt);
HLOCAL la = GlobalAlloc(LMEM_MOVEABLE,l+1);
void* dest = GlobalLock(la);
PImemcpy(dest,txt,l+1);
GlobalUnlock(la);
if(!SetClipboardData(CF_OEMTEXT,la))
{
__asm int 3;
}
CloseClipboard();
}
I have tried CF_TEXT, CF_OEMTEXT, CF_UNICODE, I have tried NULL and GetDesktopWindow() when opening the clipboard
nothing seems to work. Edit: the above code always 'works' it never errors, it just never does what I want!
How to Set text on clipboard
CString source;
//put your text in source
if(OpenClipboard())
{
HGLOBAL clipbuffer;
char * buffer;
EmptyClipboard();
clipbuffer = GlobalAlloc(GMEM_DDESHARE, source.GetLength()+1);
buffer = (char*)GlobalLock(clipbuffer);
strcpy(buffer, LPCSTR(source));
GlobalUnlock(clipbuffer);
SetClipboardData(CF_TEXT,clipbuffer);
CloseClipboard();
}
How to get text off of the clipboard
char * buffer;
if(OpenClipboard())
{
buffer = (char*)GetClipboardData(CF_TEXT);
//do something with buffer here
//before it goes out of scope
}
CloseClipboard();
You should just try using Raymond's helper function for SetClipboardData
.
Part of the problem could be you're using LMEM_MOVEABLE
with GlobalAlloc
, when you should be using GMEM_MOVEABLE
, but I haven't verified this.
I had to empty the clipboard first calling EmptyClipboard()
I think this is because, of all the CF_XXX I tried, I didn't pick the most 'default' one for text.
the idea being, you can copy an image, then copy text, and they both get put in the clipboard, so you can then go to an image program, hit paste, and it will paste the image, then go to a text program, hit paste, and it will paste the text.
hence I believe my problem was I wasn't picking a 'default' text format, it was just getting added on to the clipboard behind something in the more 'default' format and so when ever you hit paste in a program, it picked the more 'default' formatted thing to paste.
so yeah, my not entirely ideal fix was to just add EmptyClipboard() after OpenClipboard(), this causes everything to be deleted out of the clipboard, and programs to default to pasting my not entirely default format text.
精彩评论