delphi - 如何让我的组件检测鼠标位置?

标签 delphi delphi-2010

我想编写一个小组件来显示当前控制鼠标所在的位置。 当它发现所选控件时,它应该触发消息(例如)。

但是我不知道应该怎么做才能始终获取鼠标的位置。 这就是我所得到的:

  TMouseOverControl = class(TComponent)
  private
    fActive: Boolean;
    fControl: TWinControl;
  public
    constructor Create(AOwner: TComponent); override;
    procedure Loaded; override;
    procedure SpotIt;
  published
    property Active: Boolean read fActive write fActive;
    property Control: TWinControl read fControl write fControl; // when mouse is over this control show me the message
  end;

constructor TMouseOverControl.Create(AOwner: TComponent);
begin
  // nothing interesting here
  // don't have control property here - so overrided the loaded method
  inherited;
end;

procedure TMouseOverControl.Loaded;
begin
  inherited;

  //  TForm(Owner).Mo.... := SpotIt.... 
  //  what should i do to make it work?
 end;

 procedure TMouseOverControl.SpotIt;
 begin
// IsMouseOverControl is easy to implement
// http://delphi.about.com/od/delphitips2010/qt/is-some-delphi-tcontrol-under-the-mouse.htm
       if IsMouseOverControl(Control) then 
         ShowMessage('Yep, U got it!');
     end;

有什么想法吗?

最佳答案

那么你只需要在鼠标移动时检查/更新。因此,您可以使用 TApplicationEvents 跟踪 WM_MOUSEMOVE 消息。

// Edit: these variables are intended to be private fields of the component class
var
  FAppEvents: TApplicationEvents;
  FFoundControl: Boolean;
  FCurrentControl: TWinControl;

procedure TMyComponent.HandleAppMessage(var Msg: tagMSG; var Handled: Boolean);
var
  Control: TWinControl;
begin
  if (Msg.message = WM_MOUSEMOVE) and not FFoundControl then
  begin
    Control:= FindControl(Msg.hwnd);
    if Assigned(Control) then
    begin
      FCurrentControl:= Control;
      FFoundControl:= True;
    end;
  end else
  if (Msg.message = WM_MOUSELEAVE) then
    FFoundControl:= False;
end;

procedure TMyComponent.FormCreate(Sender: TObject);
begin
  FAppEvents:= TApplicationEvents.Create(nil);
  FAppEvents.OnMessage:= HandleAppMessage;
end;

这当然可以优化,例如同时检查 WM_MOUSELEAVE,这样您就不必在每次鼠标移动时FindControl。此解决方案适用于 TWinControls 及其后代。

编辑:使用了 WM_MOUSELEAVE。

关于delphi - 如何让我的组件检测鼠标位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6913326/

相关文章:

delphi - 替换 TObjectList 中的对象并释放它(Delphi7)

delphi - 在运行时从页面控件中删除选项卡

c# - 当 Delphi 类型为 "out PChar"时,我应使用什么 C# 参数类型?

c - 在 Delphi 中加入 16 位整数以生成 32 位整数?

delphi - 可以生成 PDF/A 兼容文件的报告生成器

ios - 如何使用 RAD Studio FireMonkey 在 iOS 和 Android 上启动导航应用程序?

delphi - Delphi 2010 中的 TIdHashSHA1.HashStream 是否损坏?

delphi - 为什么我的 Delphi 2010 资源 dll 文件是 ANSI 编码的

delphi - 如何混合 Mp3 文件

delphi - 对象构造函数的 "double call"是可以接受的