Advanced Windows API - AllowSetForegroundWindow()


Since Windows 98 the system restricts which windows are able to change the foreground window which means that using the SetForegroundWindow (MSDN) function is only possible under certain conditions.

For some situations another process must be able to set the foreground window. A good example where this is necessary is a custom system tray implementation. When a window is hidden and the user clicks on the tray icon a message is send to that window. The process which owns the window is now supposed to display it and send it to the foreground, but it can't do this because the focus is in another process (the system tray where the user clicked the tray icon). So the process with the system tray must allow the other process to change the foreground window.

Giving permission to a process which will temporary enable it to change the foreground window can be done by using the AllowSetForegroundWindow (MSDN) function.

Delphi Implementation:

  function AllowForegroundWindow(wnd : hwnd) : boolean;
  var
    PID: DWORD;
  begin
    GetWindowThreadProcessId(wnd, @PID);
    result := AllowSetForegroundWindow(PID);
  end;