Thursday, August 27, 2009

Drag-and-Drop in C on Windows, the easy way

OK, yeasterday I published a post where I complained about the complexities of Drag-and-Drop in plain C on Windows, and how this was related to Object Orientation gone bad. Why do you need three or 4 objects, jsut to drag a string of text from one place to another?

Well, then, if you agree that this is outrageous, I have help for you now. I just published my plain C library that does just this. You simple Win32 C program need not worry about OLE or COM. About IDataObject or interfaces or any of that stuff. Just usse hardcore C, like all macho developers like myself do. You need my library though, and I admit I AM cheating a bit in it, but actually, it does the trick and it follows the rules, both from COM/OLE and Win32 points of views.

Now, to drag and receive a text string, you need my library and you need to call 4 plain C functions or so, nuthin' else: Init the library, register as a target for a drop, start dragging and cleanup as a target for a drop. Then you need to handle the drop itself of course, but this is easy enough.

So the help is now available on Sourceforge and there is the source for the library, a Visual Studio project for this, complete with a sample, and a full PDF document describing the whole thing.

So, happy hacking, and don't drag your feet!
/Karlsson

1 comment:

anton.maurovic.com said...

Hi Anders, thanks for the library. It's quite convenient, and easily to follow to see what's happening under the hood.

Just one thing: I've found a bug when using the library in UNICODE mode.

The function CreateMyDropSourceText uses _tcslen to get the string length for GlobalAlloc. _tcslen returns the number of characters in the string, not the number of bytes. Consequently, in UNICODE mode, the GlobalAlloc call will allocate a buffer that is too small and lead to buffer overrun.

Also, CreateMyDropSourceText only uses CF_TEXT format; it doesn't have an option for CF_UNICODETEXT.

Because of these two factors, I suggest changing the function's "pText" argument from "LPCTSTR" to "LPCSTR". This will direct the caller to always use ANSI (8-bit) strings with CreateMyDropSourceText. Then, use strlen instead of _tcslen, and strcpy instead of _tcscpy.