How to paste custom format clipboard data into TMemo?

This question relates to this along with its accepted answer posted here on stackoverflow.

I do not feel comfortable programming the Windows API.

Studying the EasyGPS path Topografix handles clipboard manipulations, I found that it uses its own clipboard format called GPX , which is actually plain text ( GPX more precisely). Use of Clipboard.AsText is excluded.

I stumble at this point:

 program ProbeClipboard; {$APPTYPE CONSOLE} uses SysUtils, Windows, ClipBrd; var CF_GPX: Cardinal; ClipboardData: THandle; begin CF_GPX:=RegisterClipboardFormat('GPX'); if ClipBoard.HasFormat(CF_GPX) then begin Writeln('GPX format available in clipboard'); // OpenClipboard(0); ClipboardData := GetClipboardData(CF_GPX); if ClipboardData = 0 then raise Exception.Create('Clipboard data Error'); /// How to use GlobalLock and GlobalUnLock /// so that I can paste the Clipboard data /// to a TMemo instance for example CloseClipboard; end; end. 

Please help me fix this program.

+2
source share
1 answer

I would write it like this:

 program ProbeClipboard; {$APPTYPE CONSOLE} uses SysUtils, Windows, ClipBrd; var CF_GPX: Cardinal; ClipboardData: Windows.HGLOBAL; Ptr: Pointer; Size: DWORD; begin CF_GPX := RegisterClipboardFormat('GPX'); Clipboard.Open; try if Clipboard.HasFormat(CF_GPX) then begin Writeln('GPX format available in clipboard'); ClipboardData := Clipboard.GetAsHandle(CF_GPX); if ClipboardData=0 then RaiseLastOSError; Ptr := Windows.GlobalLock(ClipboardData); if Ptr=nil then RaiseLastOSError; try Size := Windows.GlobalSize(ClipboardData); //Ptr now points to a memory block of Size bytes //containing the clipboard data finally Windows.GlobalUnlock(ClipboardData); end; end; finally Clipboard.Close; end; end. 

Note that I have moved the clipboard Open command, which blocks the clipboard outside the test for the CF_GPX format. That is, to avoid the race condition that exists in your code. In your code, the clipboard can be changed between a call to HasFormat and a call to OpenClipboard .

I also used the Clipboard class. This class has everything you need, and you do not need to use the original Win32 clipboard API.

I even checked the error!

+5
source

Source: https://habr.com/ru/post/1390491/


All Articles