Delphi 7: How to copy non-latin text to clipboard? (convert to Unicode?)
delphi, delphi-7, unicode, winapi
Solution
Convert the text to Unicode by whatever means you see fit. In Delphi 7 that typically involves using `WideString`.
Once you have the text encoded as UTF-16, for instance in a `WideString`, you need to call `SetClipboardData` using the `CF_UNICODETEXT` clipboard format. This is wrapped by Delphi as the `SetAsHandle` method of the global `Clipboard` object.
I've not tested it, but this function should set you on the way:
uses
Windows, Clipbrd;
procedure SetClipboardText(const Text: WideString);
var
Count: Integer;
Handle: HGLOBAL;
Ptr: Pointer;
begin
Count := (Length(Text)+1)*SizeOf(WideChar);
Handle := GlobalAlloc(GMEM_MOVEABLE, Count);
Try
Win32Check(Handle<>0);
Ptr := GlobalLock(Handle);
Win32Check(Assigned(Ptr));
Move(PWideChar(Text)^, Ptr^, Count);
GlobalUnlock(Handle);
Clipboard.SetAsHandle(CF_UNICODETEXT, Handle);
Except
GlobalFree(Handle);
raise;
End;
end;
Problem
I have code like this to copy some text to clipboard. ``` uses Clipbrd; var text: string; begin text := 'Some non-latin text, for example Russian: Привет!' Clipboard.AsText := text; end; ``` Win7-8 OS, Russian locale (and format) set in OS Region settings, Delphi 7. The problem is that it works only when I switch (shift+alt) to Russian keyboard layout when copying. Otherwise it will be pasted as `"Ïðèâåò!"` instead of `"Привет!"`. How can I fix that? I think that I need somehow convert text to Unicode and call Unicode clipboard copy function from WinAPI? But how to do that?