用户拖动时突出显示组件

时间:2016-09-05 10:57:33

标签: delphi drag-and-drop

我试图实现一个简单的拖放面板,用户可以从Windows资源管理器中删除文件。在找到this线程后,基本功能已经正常工作。

现在我正在尝试更改面板的颜色,同时用户正在拖动文件。我尝试使用OnDragOver,但没有任何反应。我做错了什么?

这是我目前的代码:

unit main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ShellApi,
  Vcl.ExtCtrls, Vcl.Imaging.pngimage;

type
   TPanel = class(Vcl.ExtCtrls.TPanel)
     protected
       procedure WMDropFiles(var Message: TWMDropFiles); message WM_DROPFILES;
       procedure CreateWnd; override;
       procedure DestroyWnd; override;
     end;

  TfrmMain = class(TForm)
    panFileDrop: TPanel;
    lblFileName: TLabel;
    procedure panFileDropDragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
  private
    { Private-Deklarationen }
  public
    { Public-Deklarationen }
  end;

var
  frmMain: TfrmMain;

implementation

{$R *.dfm}

procedure TPanel.CreateWnd;
begin
   inherited;
   DragAcceptFiles(Handle, true);
end;

procedure TPanel.DestroyWnd;
begin
   DragAcceptFiles(Handle, false);
   inherited;
end;

procedure TPanel.WMDropFiles(var Message: TWMDropFiles);
var
  c: integer;
  fn: array[0..MAX_PATH-1] of char;
begin

  c := DragQueryFile(Message.Drop, $FFFFFFFF, fn, MAX_PATH);

  if c <> 1 then
  begin
    MessageBox(Handle, 'Too many files.', 'Drag and drop error', MB_ICONERROR);
    Exit;
  end;

  if DragQueryFile(Message.Drop, 0, fn, MAX_PATH) = 0 then Exit;

  frmMain.lblFileName.Caption := fn;

end;

procedure TfrmMain.panFileDropDragOver(Sender, Source: TObject; X, Y: Integer;
  State: TDragState; var Accept: Boolean);
begin
   panFileDrop.Color := $00d4d3d2;
end;

end.

1 个答案:

答案 0 :(得分:4)

问题
德尔福的Drag'n'drop概念与COM拖拽无关 Borland在同一应用程序中实现了轻量版拖放功能 这非常有效,但不支持应用程序之间的DnD操作。 COM拖放需要您使用操作系统注册放置目标并接受相关的鼠标消息。在任何时候,COM拖放都不会产生标准的OnDragOver事件 在the documentation这种混乱的来源时,我担心it does not make clear会产生误导。

您正在将基于Windows消息的代码TPanel.WMDropFiles(var Message: TWMDropFiles)与Borland的实现混合使用,仅供应用程序内使用:TfrmMain.panFileDropDragOver(...)
这两个选项存在于平行宇宙中 如果你想用COM方式,你需要一直使用COM。

解决方案
在您完成COM并需要实现WMDropFiles以及所需的所有复杂性之前,IDropTarget选项仍然是一个“轻量级”解决方案。

我对你的问题的回答是不要发明你自己的拖放,而是继续进行intertubes并下载:https://github.com/DelphiPraxis/The-Drag-and-Drop-Component-Suite-for-Delphi

这是Anders Melander着名套房的最新版本,曾经是:http://melander.dk/delphi/dragdrop/

这实现了基于COM的拖放操作,一次解决了所有问题 它本身就是美丽代码的一个很好的例子 以special note of the demos为准。 shelldragdrop的东西应该涵盖你的用例。

您想了解更多吗?
http://delphi.about.com/od/vclusing/a/dragdrop.htm

相关问题