How can I copy listbox selection to clipboard?

I've been chipping away at a small program for a few days now (thanks to those that have helped!). It is a small parsing program that helps swap out one orthography (spelling system) for another so we can read it easier.

I am using a listbox without making a full-blown class for it. I have my parser populate the listbox with multiple possibilities so I can go over them. I've also figured out how to delete a selected item from the listbox as I eliminate them. But what I'd like to do now is take the string (wstring) from the listbox and copy it to the clipboard. I'm not sure how to get at the string from the listbox. I've found things like LB_ADDSTRING, LB_DELETESTRING, etc. but nothing that tells me that I'm getting at the string itself.

Also, I've found some mention of a clipboard class but not sure what I am supposed to do with it to get it going. Is there a way to work with the clipboard without using a clipboard class like I did with the listbox?

I'm using Visual Studio 2010.
Send LB_GETTEXT message to get the text.

To copy to clipboard, you can use the following snippet:
const wchar_t* output = L"Test";
const size_t len = (wcslen(output) + 1) * sizeof (wchar_t);
HGLOBAL hMem =  GlobalAlloc(GMEM_MOVEABLE, len);
memcpy(GlobalLock(hMem), output, len );
SetClipboardData(CF_UNICODETEXT, hMem);
you can use the following snippet

Though preferably with error handling added; OpenClipboard will fail if another app already holds the clipboard.

Also note that (from remarks in MSDN article.)

If an application calls OpenClipboard with hwnd set to NULL, EmptyClipboard sets the clipboard owner to NULL; this causes SetClipboardData to fail.


Now, I'm not sure it always happens; but you should really pass the HWND of your main app window to OpenClipboard, not NULL (aka 0).

(If using the clipboard from a console app, use GetConsoleWindow to obtain the required HWND.)

Last edited on
That worked! Thank you!

I'm not exactly sure about how to go about the error handling and I agree that it is definitely something I would want. Any recommendations on what I should look for?
Topic archived. No new replies allowed.