用API函数FindWindow()找同样的窗口标题,如果返回0则说明没有实例运行,如果返回非0说明有实例已经运行(返回的是它的句柄),则将自己退出。

解决方案 »

  1.   

    unit un_DoIExist;interfaceuses Windows,SysUtils,Classes;function DoIExist(WndTitle : String) : Boolean;implementationfunction DoIExist(WndTitle : String) : Boolean;
    var
      hSem    : THandle;
      hWndMe  :HWnd;
    //  hWndPrev : HWnd;
      semNm,
      wTtl    : Array[0..256] of Char;
    begin  Result := False;  //Initialize arrays
      StrPCopy(semNm, WndTitle);
      StrPCopy(wTtl, WndTitle);  //Create a Semaphore in memory - If this is the first instance, then
      //it should be 0.
      hSem := CreateSemaphore(nil, 0, 1, semNm);  //Now, check to see if the semaphore exists
      if ((hSem <> 0) AND (GetLastError() = ERROR_ALREADY_EXISTS)) then
      begin
        CloseHandle(hSem);
        //We'll first get the currently executing window's handle then change its title
        //so we can look for the other instance
        hWndMe := FindWindow(nil, wTtl);
        SetWindowText(hWndMe, 'zzzzzzz');
        //What we want to do now is search for the other instance of this window
        //then bring it to the top of the Z-order stack.
        hWndMe := FindWindow(nil, wTtl);
        if (hWndMe <> 0) then
        begin
          if IsIconic(hWndMe) then
            ShowWindow(hWndMe, SW_SHOWNORMAL)
          else
           SetForegroundWindow(hWndMe);
        end;
        Result := True;
          //Could put the Halt here, instead of in the FormCreate method,
        //unless you want to do some extra processing.
        //Halt;
      end;
    end;end.
    //在主窗口创建时加入
      Self.caption:='数据服务管理';
      if DoIExist(Self.Caption) then Halt;
      

  2.   

    先在mainform中声明Hmutex: THandle;
    然后在*.dpr 文件中:
      Hmutex := CreateMutex(nil, false, '程序名');
      if not (waitForSingleObject(hmutex, 0) <> wait_timeout) then
        begin
          Application.MessageBox('此程序已经运行,不能再次打开!', '警告!', MB_ICONERROR);
          halt;
        end
      else
    ;;;;;