How can I assign clipboard text to a variable in c++?
Question
I've written a program that highlights numbers and copies them. I would like to be able to do some basic math with the copied text, such as multiplication or addition, but I can't figure out how to assign the clipboard data to a variable. Basically, I would like to be able to copy a number, assign it to variable "a", then repeat with variable "b" and multiply the two together. I have figured out how to select and copy the number so that part isn't an issue. Any help would be appreciated, even a completely different approach than what I have tried.
Here is my latest attempt at the problem:
HANDLE clip0;
OpenClipboard(NULL);
EmptyClipboard();
clip0 = GetClipboardData(CF_TEXT);
variable = (char)clip0;
CloseClipboard();
where "variable" is the variable.
Whenever I run the program and tell it to output "variable", it returns the value of 0.
another attempt I made was this:
HANDLE clip1;
if (OpenClipboard(NULL))
clip1 = GetClipboardData(CF_TEXT);
variable = (char)clip1;
CloseClipboard();
but "variable" would always take on the value of -8
La solution
The text content of the clipboard is a c-string pointed to by c.
if(OpenClipboard(NULL) != FALSE)
{
HANDLE clip0 = GetClipboardData(CF_TEXT);
if(clip0 != NULL)
{
char *c = reinterpret_cast<char*>(GlobalLock(clip0));
// Use c before it goes out of scope
...
GlobalUnlock(clip0);
}
CloseClipboard();
}
Autres conseils
You need to call GlobalLock(clip0)
to get a pointer to the data, rather than casting the handle. Then, when you're done, call GlobalUnlock
to release the pointer.
OpenClipboard(NULL);
HANDLE clip0 = GetClipboardData(CF_TEXT);
char* p=(char*)GlobalLock(clip0);
variable=*p;
GlobalUnlock(clip0);
CloseClipboard();