Bring previous application instance to front

I hide my application to the system tray, then try to prevent another instance of the application to be run but are unable to bring the first instance to the front again.

Here is my code to hide the application to the system tray:
  ShowWindow(Application.Handle, SW_HIDE);
  ShowWindow(Application.MainForm.Handle, SW_HIDE);

to prevent I use:
  Mutex := CreateMutex(nil, False, AppTitle);
  if (GetLastError = ERROR_ALREADY_EXISTS) or
     (Mutex = 0) then
     Application.Terminate;

But how do I bring my previous instance of my application to the front?

Thanx in advance!
skynergyAsked:
Who is Participating?
 
DaFoxConnect With a Mentor Commented:
Hi.

// OnceOnly by Peter Below
Unit OnceOnly;

Interface

Function AlreadyRunning(const AppTitle: String): Boolean;

Implementation

Uses Messages, Windows, Sysutils;

var
  mutex: THandle = 0;

function AlreadyRunning(const AppTitle: String): Boolean;
var
  wnd: HWND;
begin
  mutex := CreateMutex( nil, false, PChar(StringReplace(AppTitle, ' ', '_', [rfReplaceAll] )));
  if mutex = 0 then Result := false else Result := GetLastError = ERROR_ALREADY_EXISTS;
  if Result then
  begin
    wnd := FindWindow('TApplication', PChar(AppTitle));
    if (wnd <> 0) then
    begin
      if IsIconic(wnd) then SendMessage(wnd, WM_SYSCOMMAND, SC_RESTORE, 0);
      SetForegroundWindow(wnd);
    end;
  end;
end;

initialization

finalization
  if (mutex <> 0) then CloseHandle(mutex);
end.


Markus
1
 
ziolkoCommented:
You have to use FindWindow() to find handle of main form of previous instance and then call ShowWindow()
ziolko.
0
All Courses

From novice to tech pro — start learning today.