//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop
#include <tchar.h>
//---------------------------------------------------------------------------
USEFORM("MainForm.cpp", frmMultiEditorMain);
//---------------------------------------------------------------------------

/*
  Thanks to Neil Rubenking's book 'Delphi Programming Problem Solver'
  Pages 461-462 show how to use Mutexes to detect multiple instances.
  This has since been modified and is not quite the same. (The least
  of which is that I've converted it from Delphi to C++.)

  This is very Windows-specific code so consult the MSDN for details
  about the API calls.
*/

HANDLE Mutex;

void CheckPrevInst(void)
{
  HWND ExistingWnd = 0;
  Mutex = CreateMutex(NULL, false, NULL);

    // If other instance is still initializing, wait a while. Bail out if too long.
  if (WaitForSingleObject(Mutex, 5000) == WAIT_TIMEOUT)
    goto cleanup;

    // If an instance is already running, get its window handle
  ExistingWnd = FindWindow("TfrmMultiEditorMain", 0);

    // Got the main window, now show it (bring it to the foreground)
  if (ExistingWnd != 0)
  {
    if (IsIconic(ExistingWnd))
      ShowWindow(ExistingWnd, SW_SHOWNORMAL);
    else
      SetForegroundWindow(ExistingWnd);

      // This instance has nothing to do now.
    goto cleanup;
  }
  return;

cleanup:
  ReleaseMutex(Mutex);
  CloseHandle(Mutex);
  exit(0);
}

WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
  try
  {
    try
    {
      CheckPrevInst(); // This won't return if an instance is already running

      Application->Initialize();
      Application->MainFormOnTaskBar = true;
      Application->CreateForm(__classid(TfrmMultiEditorMain), &frmMultiEditorMain);
      Application->Run();
    }
    catch (Exception &exception)
    {
      Application->ShowException(&exception);
    }
    catch (...)
    {
      try
      {
        throw Exception("");
      }
      catch (Exception &exception)
      {
        Application->ShowException(&exception);
      }
    }
  }
  __finally
  {
    ReleaseMutex(Mutex);
    CloseHandle(Mutex);
  }
  return 0;
}
//---------------------------------------------------------------------------