Subversion Repositories delphiutils

Rev

Blame | Last modification | View Log | RSS feed

  1. unit Functions;
  2.  
  3. interface
  4.  
  5. uses
  6.   SysUtils, Windows;
  7.  
  8. function ForceForegroundWindow(hwnd: THandle): Boolean;
  9.  
  10. implementation
  11.  
  12. // Ref: http://www.swissdelphicenter.ch/de/showcode.php?id=261
  13.  
  14. function ForceForegroundWindow(hwnd: THandle): Boolean;
  15. const
  16.   SPI_GETFOREGROUNDLOCKTIMEOUT = $2000;
  17.   SPI_SETFOREGROUNDLOCKTIMEOUT = $2001;
  18. var
  19.   ForegroundThreadID: DWORD;
  20.   ThisThreadID: DWORD;
  21.   timeout: DWORD;
  22. begin
  23.   if IsIconic(hwnd) then ShowWindow(hwnd, SW_RESTORE);
  24.  
  25.   if GetForegroundWindow = hwnd then Result := True
  26.   else
  27.   begin
  28.     // Windows 98/2000 doesn't want to foreground a window when some other
  29.     // window has keyboard focus
  30.  
  31.     if ((Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion > 4)) or
  32.       ((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and
  33.       ((Win32MajorVersion > 4) or ((Win32MajorVersion = 4) and
  34.       (Win32MinorVersion > 0)))) then
  35.     begin
  36.       // Code from Karl E. Peterson, www.mvps.org/vb/sample.htm
  37.       // Converted to Delphi by Ray Lischner
  38.       // Published in The Delphi Magazine 55, page 16
  39.  
  40.       Result := False;
  41.       ForegroundThreadID := GetWindowThreadProcessID(GetForegroundWindow, nil);
  42.       ThisThreadID := GetWindowThreadPRocessId(hwnd, nil);
  43.       if AttachThreadInput(ThisThreadID, ForegroundThreadID, True) then
  44.       begin
  45.         BringWindowToTop(hwnd); // IE 5.5 related hack
  46.         SetForegroundWindow(hwnd);
  47.         AttachThreadInput(ThisThreadID, ForegroundThreadID, False);
  48.         Result := (GetForegroundWindow = hwnd);
  49.       end;
  50.       if not Result then
  51.       begin
  52.         // Code by Daniel P. Stasinski
  53.         SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, @timeout, 0);
  54.         SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(0),
  55.           SPIF_SENDCHANGE);
  56.         BringWindowToTop(hwnd); // IE 5.5 related hack
  57.         SetForegroundWindow(hWnd);
  58.         SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(timeout), SPIF_SENDCHANGE);
  59.       end;
  60.     end
  61.     else
  62.     begin
  63.       BringWindowToTop(hwnd); // IE 5.5 related hack
  64.       SetForegroundWindow(hwnd);
  65.     end;
  66.  
  67.     Result := (GetForegroundWindow = hwnd);
  68.   end;
  69. end;
  70.  
  71. end.
  72.