耶,耶,耶,耶,耶,耶,耶,耶程序只允许执行一次,即是说,已经运行了程序,不能再次执行第二次,如下代码:CreateMutex(nil,True,'程序名');   
if GetLastError = ERROR_ALREADY_EXISTS then   
  begin   
     showmessage('我日,你已经在运行中了,还想同时第二次...');
     Halt;   
  end;程序里还有一个按钮Button,功能是:重新启动 理所当然,见名知义,就不须多解释这个了....现在问题是:那么这个Button,怎么搞了??? 

解决方案 »

  1.   

    用几个api也可以实现,但是偶尔会报错,下面的安全
      procedure RunAgain;
      var
        f:TextFile;
        fn:String;
      begin
        frmShowProcessing.ShowCurrentProcess('稍候软件将重启动');
        try
          fn := ExtractFilePath(Application.ExeName)+'tmp\ReStart.bat';
          AssignFile(f,fn);
          Rewrite(f);
          Writeln(f,'ping 127.0.0.1 -n 6 ');
          Writeln(f,'cd '+ExtractFilePath(Application.ExeName));
          Writeln(f,ExtractFileName(Application.ExeName));
          CloseFile(f);
          Winexec(Pchar(fn),sw_hide);
          //Application.Terminate;
          sleep(1000);
        finally
          frmShowProcessing.Close;
        end;
      end;
      

  2.   


    procedure RestartProgram;
    var
      HWndDemo:THandle;
    begin
      HWndDemo:=FindWindow(nil, pchar('project1'));
      If HWndDemo<>0 Then
      SendMessage(HWndDemo, WM_CLOSE, 0, 0);//不要用Close
      ShellExecute(Application.Handle,nil,PChar('project1'),nil,nil,SW_SHOWNORMAL);
    end;
      

  3.   

    第三行,注释写错了(去掉不要用Close)
      

  4.   

    一关一开不就结了。liangpei2008 的应该没有问题的。
      

  5.   

    Project部分的代码, 用全局变量MutexHandle(位于Unit中)来保存Mutexprogram Project1;uses
      Forms,
      Windows,
      Unit1 in 'Unit1.pas' {Form1};{$R *.res}begin
      MutexHandle := CreateMutex(nil, True, '程序名');
      if GetLastError = ERROR_ALREADY_EXISTS then
      begin
        MessageBox(0, '我日,你已经在运行中了,还想同时第二次...', '提示', MB_OK);
        Halt;
      end;
      Application.Initialize;
      Application.CreateForm(TForm1, Form1);
      Application.Run;
    end.
    Unit1的代码:unit Unit1;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls, ShellAPI;var
      MutexHandle : THandle;type
      TForm1 = class(TForm)
        Button1: TButton;
        procedure Button1Click(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;var
      Form1: TForm1;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
    begin
      //释放Mutex
      ReleaseMutex(MutexHandle);
      //调用自己
      ShellExecute(0, nil, PChar(Application.ExeName), nil, nil, SW_SHOWNORMAL);
      //结束当前程序
      Application.Terminate;
    end;end.
      

  6.   

    楼主 真是放荡不拘啊  哇哈哈 好玩 if GetLastError = ERROR_ALREADY_EXISTS then 
      begin 
        showmessage('我日,你已经在运行中了,还想同时第二次...');
        Halt; 
      end; 2楼和 6楼都不错 我一般偷懒 用2楼的方法