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.
Asked
Active
Viewed 9,138 times
4 Answers
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 ...

gabr
- 26,580
- 9
- 75
- 141

Remy Lebeau
- 555,201
- 31
- 458
- 770
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
.

Andreas Rejbrand
- 105,602
- 8
- 282
- 384
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.

Hamish_Fernsby
- 558
- 1
- 7
- 28