You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Delphi中获取Sender对象位置遇不可访问值,求正确实现方式

解决Delphi中OnMouseUp事件里Sender转TImage的问题

你的问题核心是错误地使用了指针类型和ClassInfo,Sender本身就是触发事件的TImage实例,不需要用指针绕弯,直接类型转换就能访问它的属性。

错误原因分析

  • 声明Current:^TImage完全没必要,Delphi里控件对象本身就是引用类型,不需要额外用指针指向它
  • Sender.ClassInfo返回的是类的元信息(RTTI数据),不是对象实例的指针,所以赋值给^TImage类型变量必然类型不匹配

正确实现代码

直接把Sender转换成TImage类型,推荐用as操作符(会自动检查类型合法性,避免类型转换错误):

procedure THeaderFooterwithNavigation.DraggableImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var 
  Current: TImage;
begin
  ActiveDrag.Remove(Sender);
  // 类型转换:把Sender转为TImage实例
  Current := Sender as TImage;

  // 现在可以正常访问Current的所有属性了
  if ((Image12.Position.X) < (Current.Position.X + Current.Width/2)) and 
     ((Current.Position.X + Current.Width/2) < (Image12.Position.X + Image12.Width)) then
  begin
    if ((Image12.Position.Y) < (Current.Position.Y + Current.Height/2)) and 
       ((Current.Position.Y + Current.Height/2) < (Image12.Position.Y + Image12.Height)) then
    begin
      Current.Position.X := Image12.Position.X;
      Current.Position.Y := Image12.Position.Y;
    end;
  end;
end;

补充说明

如果确定Sender一定是TImage类型,也可以用强制转换Current := TImage(Sender),但as操作符更安全——如果Sender不是TImage,会抛出异常提醒你,避免潜在的内存访问错误。

内容的提问来源于stack exchange,提问作者Luan Zeqiri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 03:22:41