In the example below, I successfully overwrote data. Does that mean the data is stored in local memory rather than global memory? So GetClipboardData()
makes a local copy of the clipboard's memory? If that is the case, then what is the point of requiring the use of GlobalLock()
before reading that memory. Also, why don't I have to free()
that local memory?
This is a excerpt from the section called: Getting Text from the Clipboard
"The handle you receive from GetClipboardData doesn't belong to your program—it belongs to the clipboard. ... You can't free that handle or alter the data it references. If you need to have continued access to the data, you should [manually using malloc()] make a copy of the memory block."
#include <stdio.h>
#include <windows.h>
int main(void)
{
if (IsClipboardFormatAvailable(CF_TEXT) != 0)
{
if (OpenClipboard(NULL) != 0)
{
HANDLE hData = GetClipboardData(CF_TEXT);
if (hData != NULL)
{
char *content = GlobalLock(hData);
if(content == NULL)
puts("GlobalLock()");
else
{
size_t length = strlen(content);
printf("Before: %s\n", content);
FillMemory(content + (length / 2), (length / 2), '*');//Hello World!
printf("After : %s\n", content);
if (GlobalUnlock(hData) == 0)
{
if (GetLastError() != NO_ERROR)
puts("GlobalUnlock()");
}
}
}
else
{
if (GetLastError() != ERROR_SUCCESS)
puts("GetClipboardData()");
}
if (CloseClipboard() == 0)
puts("CloseClipboard()");
}
else
puts("OpenClipboard()");
}
getchar();
return 0;
}
First execution:
Before: Hello World!
After : Hello ******Second execution:
Before: Hello World!
After : Hello ******