如何将自定义格式的剪贴板数据粘贴到TMemo? [英] How to paste a custom format clipboard data into a TMemo?

查看:203
本文介绍了如何将自定义格式的剪贴板数据粘贴到TMemo?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题涉及及其接受的答案发布在stackoverflow。

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

我不太舒服在Windows API 编程。

I don't feel comfortable at Windows API programming.

浏览 EasyGPS 的方式,一个href =http://www.topografix.com/ =nofollow> Topografix 处理剪贴板操作,我发现它使用自定义的剪贴板格式命名为 GPX 实际上是纯XML文本( GPX 准确)。使用Clipboard.AsText被排除。

Exploring the way EasyGPS by Topografix handles clipboard manipulations, I discovered that it uses a custom clipboard format named GPX wich is actually plain XML text (GPX to be precise). Using Clipboard.AsText is excluded.

我在这个阶段绊倒:

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.

请帮助我修复该程序。

推荐答案

我会这样写:

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.

请注意,我移动了剪贴板打开命令,它将剪贴板锁定在 CF_GPX 格式的测试之外。这是为了避免您的代码中存在的竞争条件。在您的代码中,剪贴板可以在 HasFormat 调用和 OpenClipboard 调用之间进行修改。

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

我也专门使用了剪贴板类。这个类有你所需要的,你不需要使用原始的Win32剪贴板API。

I also used the Clipboard class exclusively. This class has all you need and you don't need to use the raw Win32 clipboard API.

我甚至把错误检入!

这篇关于如何将自定义格式的剪贴板数据粘贴到TMemo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆