Einzelnen Beitrag anzeigen

musicman56
(Gast)

n/a Beiträge
 
#4

AW: Problem beim Programmneustart mit Instanzkontrolle

  Alt 7. Nov 2013, 02:09
Hi Sir Rufo,

sag mal, wann schläfst du denn?

Klar, die Unit hat noch Verbesserungspotential. Ich gebe den Mutex auch nicht frei. Habe es auch noch nirgendwo gesehen, muss aber nichts bedeuten. Ich dachte immer, bei Programmende wird der Mutex automatisch freigegeben?

Hier mal meine Variante:

Delphi-Quellcode:
unit RuMutex;

interface

uses Windows, SysUtils;

function CreateRubinSoftwareMutex(MutexName: string): boolean;
function CreateApplicationMutex: boolean;

implementation

function StringReplace(Value: string): string;
var
  i: integer;
begin
  Result := Value;
  for i := 1 to Length(Result) do
  if not CharInSet(Result[i],['0'..'9','a'..'z','A'..'Z'])
  then Result[i] := '_';
end;

function CreateRubinSoftwareMutex(MutexName: string): boolean;
var
  LastError : DWord;
  SecurityDesc : TSecurityDescriptor;
  SecurityAttr : TSecurityAttributes;
  aName : string;
  Res : Cardinal;
begin
  Result := false;
  InitializeSecurityDescriptor(@SecurityDesc, SECURITY_DESCRIPTOR_REVISION);
  SetSecurityDescriptorDacl(@SecurityDesc, True, nil, False);
  SecurityAttr.nLength := SizeOf(SecurityAttr);
  SecurityAttr.lpSecurityDescriptor := @SecurityDesc;
  SecurityAttr.bInheritHandle := False;
  aName := 'Global\RUBiN_Software_' + StringReplace(MutexName);
  Res := CreateMutex(@SecurityAttr, True, PChar(aName));
  LastError := GetLastError;
  if (Res = 0) then raise EOSError.Create('Mutex Modul-Name <'
                         + aName+'> konnte nicht erzeugt werden. Fehler-Code:'
                         + IntToStr(LastError))
  else if (LastError <> ERROR_ALREADY_EXISTS) then Result := true;
end;

function CreateApplicationMutex: boolean;
begin
  Result := CreateRubinSoftwareMutex(ParamStr(0));
end;

end.
  Mit Zitat antworten Zitat