请问如何禁止程序二次运行?确保只有一个程序在运行。

解决方案 »

  1.   

    var
      HMutex: THandle;
    Begin
      // check if mutex already exists
      HMutex := CreateMutex(nil, False, 'This is Budded Single App Demo');
      if HMutex <> 0 then
        if WaitForSingleObject(HMutex, 0) <> WAIT_TIMEOUT then  // Owns the Mutex
          try  // try   }
            AppRun; // run your application 
          finally  // wrap up finally
            ReleaseMutex(HMutex);
          end;   // end try finally     
    end. 
      

  2.   

    http://blog.csdn.net/linzhengqun/archive/2005/12/29/564646.aspx
      

  3.   

    源代码贴上,在工程文件中,const
      AllowedInstances = 1;var
      MyAppName   : Array[0..255] of Char;
      MyClassName : Array[0..255] of Char;
      NumFound    : Integer;
      LastFound   : HWnd;
      MyPopup     : HWnd;function LookAtAllWindows(Handle: HWND; Temp: LongInt): BOOL; stdcall;
    var
      WindowName : Array[0..255] of Char;
      ClassName  : Array[0..255] of Char;
    begin
      // Go get the windows class name
      if GetClassName(Handle,ClassName,SizeOf(ClassName)) > 0 then
        // Is the window class the same?
        if StrComp(ClassName,MyClassName) = 0 then
          // Get its window caption
          if GetWindowText(Handle,WindowName,SizeOf(WindowName)) > 0 then
            // Does this have the same window title?
            if StrComp(WindowName,MyAppName)=0 then
              begin
                inc(NumFound);
                // Are the handles different?
                if Handle <> Application.Handle then
                  // Save it so we can bring it to the top later.
                  LastFound := Handle;
              end;
      Result:=true;
    end;begin
      //防止程序多实例运行
      NumFound := 0; LastFound := 0;
      // First, determine what this application's name is
      GetWindowText(Application.Handle,MyAppName,SizeOf(MyAppName));
      // Now determine the class name for this application
      GetClassName(Application.Handle,MyClassName,SizeOf(MyClassName));
      // Now count how many others out there are Delphi apps with this title
      EnumWindows(@LookAtAllWindows,0);
      if NumFound > AllowedInstances then
        // There is another instance running, bring it to the front!
        begin
          MyPopup := GetLastActivePopup(LastFound);
          // Bring it to the top in the ZOrder
          BringWindowToTop(LastFound);
          // Is the window iconized?
          if IsIconic(MyPopup) then
            // Restore it to its original position
            ShowWindow(MyPopup,SW_RESTORE)
          else
            // Bring it to the front
            SetForegroundWindow(MyPopup);
        end
      else
        // None running - allow this instance to continue
        begin
          
          Application.Initialize;
          Application.CreateForm(TDataModuleMain, DataModuleMain);
      Application.CreateForm(TFrmMain, FrmMain);
      Application.Run;
        end   ; end.
    了解否?