Mega Code Archive

 
Categories / Delphi / Examples
 

One instance w command line passing

Title: One instance w/ command line passing Question: one of many methods to restrict the number of instances of an application, and pass the command line to the already running instance Answer: .dpr file ---------- uses Forms, Windows, Messages, Clipbrd, {List of forms and what not} {$R *.RES} var mHnd : THandle; {procedure to send command line} procedure Send; var hnd : HWND; st : string; cl : TClipboard; begin hnd := FindWindow('TMnFrm',nil); if hnd 0 then begin if ParamCount = 1 then begin st := ParamStr(1); cl := Clipboard; cl.SetTextBuf(PChar(st)); SendMessage(hnd, WM_USER+UM_PassParam, Length(st), 1); end; ShowWindow(hnd,SW_SHOWNORMAL); end; end; begin Application.Initialize; Application.Title := 'MyApp'; mHnd := OpenMutex(MUTEX_ALL_ACCESS,false,'mymutt'); if mHnd 0 then begin CloseHandle(mHnd); //Thanks Andreas Send; Exit; end; mHnd := CreateMutex(nil,TRUE,'mymutt'); Application.CreateForm(TMnFrm, MnFrm); Application.Run; CloseHandle(mHnd); end. ---------------------------------------------------------------- {.pas file} unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, MPlayer, Clipbrd, ExtCtrls, ComCtrls, IniFiles; const UM_PassParam = 42; type TMnFrm = class(TForm) procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); private procedure WMUserMsg(var Msg:TMessage); message WM_USER+UM_PassParam; public end; var MnFrm: TMnFrm; implementation {$R *.DFM} {blah blah blah} // Here's the part where we read the command line from other instance procedure TMnFrm.WMUserMsg(var Msg:TMessage); var cl : TClipBoard; FNam : PChar; begin cl := Clipboard; Getmem(FNam,Msg.WParam+1); cl.GetTextBuf(FNam,Msg.WParam+1); ShowMessage:=Fnam; FreeMem(FNam); end; --------------------------------------------- So basically we just check to see if an instance is already running, and if it is, we copy the command line args to the clipboard and send a message to the other instance, then shut ourselves down I know, there are probably a couple of problems with using the clipboard that I haven't thought of yet, but I haven't yet run into any problems with it, and hey....it's a start. CJK