Reputation: 1178
I am trying to get my application to copy a character array to the clipboard so it can be pasted into an IE address bar. I am having an issue with getting this working. This is the code I am working with:
HGLOBAL glob = GlobalAlloc(GMEM_FIXED,32);
memcpy(glob,array,sizeof(array));
OpenClipboard(hDlg);
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT,glob);
CloseClipboard();
Array is declared as:
char array[500];
This will cause the program to crash. However if I switch out sizeof(array)
with a number it ok but The only 8 characters are copyied to the clipboard.
Can anyone advise me on how to solve this issue? I am targeting the Win32 API directly, not using MFC.
Upvotes: 0
Views: 1604
Reputation: 62
I created a function to save and load clipboard.
#include <Windows.h>
char* LoadClipboard()
{
static HANDLE clip;
if(OpenClipboard(NULL))
{
clip = GetClipboardData(CF_TEXT);
CloseClipboard();
}
return (char*) clip;
}
void SaveClipboard(char* text)
{
HGLOBAL global = GlobalAlloc(GMEM_FIXED,strlen(text) + 1); //text size + \0 character
memcpy(global,text,strlen(text)); //text size + \0 character
if(OpenClipboard(NULL))
{
EmptyClipboard();
SetClipboardData(CF_TEXT,global);
CloseClipboard();
}
}
Upvotes: 2
Reputation: 61462
You are copying 500 chars (sizeof(array)
) into a buffer that only has space for 32 chars. All the remaining chars trample over random data and cause the crash.
Upvotes: 2
Reputation: 101456
You are only allocating 32 bytes of global memory:
GlobalAlloc(GMEM_FIXED,32);
...and then trying to cram 500 bytes in to a 32 byte bag:
memcpy(glob,array,sizeof(array));
Change the GlobalAlloc to:
GlobalAlloc(GMEM_FIXED,sizeof(array));
Further, you are pasting the data as Unicode text (CF_UNICODETEXT
), but it's not Unicode text. I would imagine that would cause... problems.
Paste it as plain text instead:
SetClipboardData(CF_TEXT,glob);
Upvotes: 5