oMBRa Posted June 10, 2009 Posted June 10, 2009 I'm trying to copy text to the clipboard but I cant figure out what is the error, here is my code: CODE #include <Windows.h> #include <assert.h> #include <string> int main() { HGLOBAL hText; LPVOID pText; HANDLE Success; BOOL Close; BOOL Open; //char buffer char text[] = "Hello World"; int nSize = strlen(text)*sizeof(char)+1; //allocating a buffer hText = GlobalAlloc(GHND, nSize); //check for error assert(!hText == 0 ); //locking the memory pText = GlobalLock(hText); //check for error assert(!pText == 0 ); //copying the char buffer into the allocated memory memcpy(pText, static_cast<void*>(text), nSize); GlobalUnlock(hText); //opening clipboard Open = OpenClipboard(0); //check for error assert(!Open == 0 ); //setting the data into the clipboard Success = SetClipboardData(CF_TEXT, hText); //check for error assert(!Success == 0 ); //closing the clipboard Close = CloseClipboard(); //check for error assert(!Close == 0 ); return 0; }
Authenticity Posted June 11, 2009 Posted June 11, 2009 I think that the clipboard is converting the string to unicode internally and requires the memory block to be an ANSI string block, and you need to free the clipboard before you set it's data: #include <Windows.h> #include <iostream> using namespace std; int main() { HGLOBAL hText; CHAR* pText; CHAR text[] = "Hello World"; SIZE_T nSize = strlen(text)+1; hText = GlobalAlloc(GHND | GMEM_DDESHARE, nSize); if (hText) { if(pText = (CHAR*)GlobalLock(hText)) { strcpy(pText, text); GlobalUnlock(hText); if (OpenClipboard(NULL)) { EmptyClipboard(); SetClipboardData(CF_TEXT, hText); CloseClipboard(); } else cout << "Error: Could not open the clipboard\n"; } GlobalFree(hText); } else cout << "Error: Could not allocate buffer\n"; return 0; }
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now