Copying to Clipboard

Hello! I want to copy something to the clipboard. I have a simple function that does this for me, but unfortunately it crashes if what is inputted (in the string "blah") is larger than 30 characters. I believe when reading about where I got most of this code from, it was based on C, so there's likely a better option. Here's what I have though (has a dependency on the "windows.h" library, crashes at line 8):

1
2
3
4
5
6
7
8
9
10
void clip(string blah)
{
	HWND hWnd=0;	// Bool for if the clipboard is in use
	HGLOBAL glob = GlobalAlloc(GMEM_FIXED,32);	//Creates object for where data will be held
	memmove(glob,blah.c_str(),blah.size()+2);	// Copies data from string to object
	OpenClipboard(hWnd);	// Opens the clipboard, changing hWnd to something if it fails?
	EmptyClipboard();	// Empties clipbard
	SetClipboardData(CF_TEXT,glob);	// Adds data from object to clipboard
	CloseClipboard();	// Closes clipboard for other programs' use
}


So is there some other snippet of code I can use for my clip() function? Or is there a way I can append data to the clipboard (letting me recursively call this function to continuously add 30 characters until I finally have my entire string on the clipboard)?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool setClipBoardString(string source){
if(OpenClipboard(NULL))
{
	HGLOBAL clipbuffer;
	char * buffer;
	EmptyClipboard();
	clipbuffer = GlobalAlloc(GMEM_DDESHARE, source.size()+1);
	buffer = (char*)GlobalLock(clipbuffer);
	strcpy(buffer, LPCSTR(source.c_str()));
	GlobalUnlock(clipbuffer);
	SetClipboardData(CF_TEXT,clipbuffer);
	CloseClipboard();
	return true;
}
return false;
}


try this one =]

(note the source.size()+1 part)
Woooo thanks! Works with a 200+ character string!!

I just replaced the "return false;" with this, but yeah...
1
2
	Sleep(500);
	clip(source);
Last edited on
Careful! The MSDN entry for OpenClipboard states that
If an application calls OpenClipboard with hwnd set to NULL, EmptyClipboard sets the clipboard owner to NULL; this causes SetClipboardData to fail
.

Also, I usually encounter GlobalAlloc with GMEM_MOVEABLE in these situations (the deprecated GMEM_DDESHARE is only still about "to provide compatibilty with 16-bit Windows")
Topic archived. No new replies allowed.