How can I check if my application has focus?
Asked Answered
A

4

10

What I want to do is check if my application has focus because if it is not then I will popup an Alert Window just over the Notification Area to display some message to the end user.

Anabiosis answered 14/9, 2010 at 20:16 Comment(0)
E
18

Call Windows.GetForegroundWindow() and then pass the HWND to the Controls.FindControl() function. It will return a non-nil TWinControl pointer if the HWND belongs to your process. For example:

if FindControl(GetForegroundWindow()) <> nil then
  // has focus ...
else
  // does not have focus ...
Enlistee answered 14/9, 2010 at 20:40 Comment(0)
O
5

D2007 has this useful property

if Application.Active then
//
Onrush answered 13/6, 2016 at 14:38 Comment(0)
B
4

If your application consists of a single form, then

GetForegroundWindow = Handle

will suffice. The expression above is true if and only if the your form is the foreground window, that is, if keyboard focus belongs to a control on this form (or to the form itself).

If your application consists of a number of forms, simply loop through them and check if any of them matches GetForegroundWindow.

Brownedoff answered 14/9, 2010 at 20:21 Comment(0)
L
0

A slight variation on Remys response is:

Var
  Win: TWinControl;
Begin
  Win := FindControl(GetForegroundWindow);
  if Win <> nil then
//      StringGrid1.Row :=5;
//      StringGrid1.SetFocus;

compiled ok for me, but I found it unreliable during debug, the stringgrid.setfocus is called even when the window isn't focused causing an error.

Lydon answered 25/9, 2012 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.