我想写一个小组件,告诉我当前哪个控制鼠标。 当它发现选择的控制时,它应该发射消息(例如)。
但是我不知道我应该怎么做才能获得鼠标的位置。 这就是我所拥有的:
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;
有什么想法吗?
答案 0 :(得分:4)
嗯,你只需要在鼠标移动时检查/更新。因此,您可以使用WM_MOUSEMOVE
跟踪TApplicationEvents
条消息。
// 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。
答案 1 :(得分:0)
这样的事情怎么样:
// rectangle where you are interested to check if the mouse is into..
targetRect := Rect(0, 0, ImageZoom.Width, ImageZoom.Height);
// find out where the mouse is..
mousePosition := Point(0, 0);
GetCursorPos(mousePosition);
// find out if the point.. from screen to client.. is inside that rectangle
isMouseInside := (PtInRect(targetRect, ScreenToClient(mousePosition)));