I'm trying to make a function that will copy text to the clipboard. I'm using the Windows API. This is the code I have so far:
code:
function set_clipboard_text()
{
var tmp = "This is a test";
var l = tmp.length * 2 + 2;
if (Interop.Call("User32", "OpenClipboard", 0))
{
Interop.Call("User32", "EmptyClipboard");
var h = Interop.Call("Kernel32", "GlobalAlloc", 0x2000, l);
var p = Interop.Allocate( l );
p.WriteDWORD(0, Interop.Call("Kernel32", "GlobalLock", h));
Interop.Call("Kernel32", "lstrcpyW", p, tmp);
Interop.Call("Kernel32", "GlobalUnlock", h);
Interop.Call("User32", "SetClipboardData", 1, h)
Interop.Call("User32", "CloseClipboard");
}
}
I'm obviously going to make it set_clipboard_text(str), the way the function is now is just while I test it and try and get it to work.
I'm basing it off some C++ code that I wrote a while ago:
code:
OpenClipboard(NULL);
EmptyClipboard();
HGLOBAL h = GlobalAlloc(GMEM_DDESHARE, strlen(source)+1);
char* p = (char*)GlobalLock( h );
lstrcpy(p, source);
GlobalUnlock( h );
SetClipboardData(CF_TEXT,h);
CloseClipboard();
The function as it is now works fine, there are no errors. And text is copied to the clipboard. The problem is, this text consists of several spaces and random characters. I have a feeling it's a unicode problem but I can't see where I've gone wrong in my function, so does anyone have any ideas?