From: "Earl F. Glynn" Newsgroups: borland.public.delphi.winapi References: <3acb37a2$1_2@dnews> Subject: Re: How do I make sure only one copy of exe is running? Date: Wed, 4 Apr 2001 11:17:15 -0500 Lines: 83 Organization: efg's Computer Lab X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 5.50.4133.2400 X-MimeOLE: Produced By Microsoft MimeOLE V5.50.4133.2400 NNTP-Posting-Host: 12.75.144.5 Message-ID: <3acb4a15_1@dnews> X-Trace: dnews 986401301 12.75.144.5 (4 Apr 2001 09:21:41 -0700) Path: dnews Xref: dnews borland.public.delphi.winapi:128864 "John Bouris" wrote in message news:3acb37a2$1_2@dnews... > I know I've seen this tip somewhere but I can't find it. > > I want to stop the user from starting a second copy of my exe. Place the following in the project (.DPR) file: VAR MutexHandle: THandle; begin // Use Mutex to only allow one copy of XXXXX to be in memory at a time MutexHandle := 0; TRY MutexHandle := CreateMutex(NIL, TRUE, 'TFormXXXXX); IF GetLastError = ERROR_ALREADY_EXISTS THEN BEGIN SetForegroundWindow(FindWindow('TFormXXXXX', NIL)); CloseHandle (MutexHandle) END ELSE BEGIN Application.Title := 'XXXXX'; Application.CreateForm(TFormXXXXX, FormXXXXX); ... Application.Run; END FINALLY ReleaseMutex(MutexHandle) END end. In several Delphi PC Magazine utilities, Neil Rubenking uses a different approach. Here's how Neil prevented two instances of his recent KeyClick utility from running: TYPE THandles = Record AppHandle : HWnd; WinHandle : HWnd; end; VAR hMap : THandle; PH : ^THandles; begin hMap := OpenFileMapping(FILE_MAP_ALL_ACCESS, False, MainMapName); IF hMap = 0 THEN // first instance begin hMap := CreateFileMapping($FFFFFFFF, NIL, PAGE_READWRITE, 0, SizeOf(THandles), MainMapName); PH := MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0); Application.Initialize; Application.Title := 'KeyTick'; Application.CreateForm(TMainForm, MainForm); Application.MainForm.HandleNeeded; PH^.AppHandle := Application.Handle; PH^.WinHandle := Application.Mainform.Handle; Application.Run; end ELSE begin PH := MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0); SendMessage(PH^.WinHandle, regMsg, -1, -1); end; UnMapViewOfFile(PH); CloseHandle(hMap); end. In case you're interested, find complete source code for Neil's KeyClick here: http://www.zdnet.com/pcmag/stories/solutions/0,8224,2692946,00.html Or, look at any of Neil's other Delphi utilities by searching from that page. -- efg efg2@efg2.com Earl F. Glynn, Overland Park, KS USA efg's Computer Lab: http://www.efg2.com/Lab Mirror: http://homepages.borland.com/efg2lab/Default.htm