1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| unit Unique_Instance;
{
dans la projet :
Application.Initialize;
Application.Title := 'Titre du Programme';
if not UniqueInstance(Application.Title) then Exit;
Application.CreateForm(TMenuFrm, MenuFrm);
Application.Run;
}
interface
uses
forms,windows,sysutils;
type
PFindWindowStruct = ^TFindWindowStruct;
TFindWindowStruct = record
Caption: string;
ClassName: string;
WindowHandle: THandle;
end;
function UniqueInstance(Nom: String): boolean;
procedure GoMainApp(Nom: String);
function FindAWindow(ACaption: string): THandle;
function EnumWindowsProc(hWindow: hWnd;lParam : LongInt): Boolean; stdcall;
implementation
function UniqueInstance(Nom: String): boolean;
begin
CreateMutex(nil, False, PChar(Nom));
Result := GetLastError <> ERROR_ALREADY_EXISTS;
if not Result then GoMainApp(Application.Title);
end;
procedure GoMainApp(Nom: String);
var
ActifHnd: THandle;
begin
ActifHnd:= FindAWindow(Nom);
if ActifHnd <> 0 then begin
ShowWindow(ActifHnd, SW_NORMAL);
SetForegroundWindow(ActifHnd);
end;
end;
function FindAWindow(ACaption: string): THandle;
var
WindowInfo: TFindWindowStruct;
begin
with WindowInfo do begin
Caption:= ACaption;
ClassName:= '';
WindowHandle:= 0;
EnumWindows(@EnumWindowsProc, LongInt(@WindowInfo));
result:= WindowHandle;
//showmessage(IntTostr(result));
end;
end;
function EnumWindowsProc(hWindow: hWnd;lParam : LongInt): Boolean; stdcall;
var
lpBuffer: PChar;
WindowCaptionFound: bool;
ClassNameFound: bool;
begin
GetMem(lpBuffer, 255);
Result:= True;
WindowCaptionFound:= False;
ClassNameFound:= False;
try
if GetWindowText(hWindow, lpBuffer, 255) > 0 then
if Pos(PFindWindowStruct(lParam).Caption, StrPas(lpBuffer)) = 1 then begin
WindowCaptionFound:= true;
if PFindWindowStruct(lParam).ClassName = '' then
ClassNameFound:= True
else if GetClassName(hWindow, lpBuffer, 255) > 0 then
if Pos(PFindWindowStruct(lParam).ClassName, StrPas(lpBuffer)) > 0 then
ClassNameFound:= True;
end;
if (WindowCaptionFound and ClassNameFound) then begin
PFindWindowStruct(lParam).WindowHandle:= hWindow;
Result:= False;
end;
finally
FreeMem(lpBuffer, sizeof(lpBuffer^));
end;
end;
end. |
Partager