我需要与问题“如何在控件上获取光标位置?”相反的信息。问。
给定当前光标位置,如何找到表单(在我的应用程序中)和光标当前所在的控件?我需要它的句柄,以便我可以使用Windows.SetFocus(Handle)
.
作为参考,我使用的是 Delphi 2009。
我需要与问题“如何在控件上获取光标位置?”相反的信息。问。
给定当前光标位置,如何找到表单(在我的应用程序中)和光标当前所在的控件?我需要它的句柄,以便我可以使用Windows.SetFocus(Handle)
.
作为参考,我使用的是 Delphi 2009。
我在建议的解决方案(Delphi XE6/Windows 8.1/x64)中遇到了一些问题:
就我而言,这是一个问题,因为我需要在鼠标光标下找到任何可见的控件,所以我必须使用我自己的函数实现FindControlAtPos
:
function FindSubcontrolAtPos(AControl: TControl; AScreenPos, AClientPos: TPoint): TControl;
var
i: Integer;
C: TControl;
begin
Result := nil;
C := AControl;
if (C=nil) or not C.Visible or not TRect.Create(C.Left, C.Top, C.Left+C.Width, C.Top+C.Height).Contains(AClientPos) then
Exit;
Result := AControl;
if AControl is TWinControl then
for i := 0 to TWinControl(AControl).ControlCount-1 do
begin
C := FindSubcontrolAtPos(TWinControl(AControl).Controls[i], AScreenPos, AControl.ScreenToClient(AScreenPos));
if C<>nil then
Result := C;
end;
end;
function FindControlAtPos(AScreenPos: TPoint): TControl;
var
i: Integer;
f,m: TForm;
p: TPoint;
r: TRect;
begin
Result := nil;
for i := Screen.FormCount-1 downto 0 do
begin
f := Screen.Forms[i];
if f.Visible and (f.Parent=nil) and (f.FormStyle<>fsMDIChild) and
TRect.Create(f.Left, f.Top, f.Left+f.Width, f.Top+f.Height).Contains(AScreenPos)
then
Result := f;
end;
Result := FindSubcontrolAtPos(Result, AScreenPos, AScreenPos);
if (Result is TForm) and (TForm(Result).ClientHandle<>0) then
begin
WinAPI.Windows.GetWindowRect(TForm(Result).ClientHandle, r);
p := TPoint.Create(AScreenPos.X-r.Left, AScreenPos.Y-r.Top);
m := nil;
for i := TForm(Result).MDIChildCount-1 downto 0 do
begin
f := TForm(Result).MDIChildren[i];
if TRect.Create(f.Left, f.Top, f.Left+f.Width, f.Top+f.Height).Contains(p) then
m := f;
end;
if m<>nil then
Result := FindSubcontrolAtPos(m, AScreenPos, p);
end;
end;
我想FindVCLWindow
会满足你的需求。一旦你在光标下有了窗口控件,你就可以遍历父链来找到窗口所在的窗体。
如果您想知道某个 x,y 坐标的表单内的控件
采用
function TWinControl.ControlAtPos(const Pos: TPoint; AllowDisabled: Boolean;
AllowWinControls: Boolean = False; AllLevels: Boolean = False): TControl;
鉴于您似乎只对应用程序中的表单感兴趣,您可以只查询所有表单。
一旦你得到一个非零结果,你可以查询控件的句柄,代码如下
伪代码
function HandleOfControlAtCursor: THandle;
const
AllowDisabled = true;
AllowWinControls = true;
AllLevels = true;
var
CursorPos: TPoint
FormPos: TPoint;
TestForm: TForm;
ControlAtCursor: TControl;
begin
Result:= THandle(0);
GetCursorPos(CursorPos);
for each form in my application do begin
TestForm:= Form_to_test;
FormPos:= TestForm.ScreenToClient(CursorPos);
ControlAtCursor:= TestForm.ControlAtPos(FormPos, AllowDisabled,
AllowWinControls, AllLevels);
if Assigned(ControlAtCursor) then break;
end; {for each}
//Break re-enters here
if Assigned(ControlAtCursor) then begin
while not(ControlAtCursor is TWinControl) do
ControlAtCursor:= ControlAtCursor.Parent;
Result:= ControlAtCursor.Handle;
end; {if}
end;
如果您愿意,这也允许您将某些形式排除在考虑之外。如果您正在寻找简单性,我会选择 David 并使用FindVCLWindow
.
PS 就我个人而言,我会使用 agoto
而不是 break,因为使用 goto 可以立即清楚 break 重新进入的位置,但在这种情况下,这不是一个大问题,因为在 break 和重新进入点之间没有语句.