如果程序已经运行了,我再打开时,他又运行多一个窗口,我想让同一个程序只运行一次,该如何?

解决方案 »

  1.   

    程序开始的时候创建一个互斥体:
    CreateMutex(nil, false, 一个字符串);
    if GetLastError=ERROR_ALREADY_EXISTS then
    begin
      Application.MessageBox('该程序只能运行一个实例','提示',MB_OK OR MB_ICONINFORMATION); 
      Application.Terminate;
    end;
      

  2.   

    var
      errNO: integer;
      hMutex: HWND;
    begin 
    hMutex := CreateMutex(nil, False, PChar(Application.Title));
      errNO := GetLastError;
      if errNO = ERROR_ALREADY_EXISTS then
      begin  // 检测是否重复运行
        MessageDlg('本软件已在运行!', mtInformation, [mbOK], 0);
        Application.Terminate; //整个程序终止
      end;
      

  3.   

    unit Unit1;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, ExtCtrls, StdCtrls, CheckLst;type
      TForm1 = class(TForm)
        procedure FormCreate(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;var
      Form1: TForm1;
      //保存Mutex句柄
      mHandle:THandle;
      PreviousInstanceWindow:HWnd;
      Project:String;
      AppName:String;
    implementation{$R *.dfm}
    procedure TForm1.FormCreate(Sender: TObject);
    beginend;initialization
      //定义自己的项目名称,作为要创建的互斥区名,最好有自己的特点以防止重复
      Project:='RunOnlyOnce_MyProject';
      //将lpMutexAttributes设为nil,bInitialOwner设为True(即本程序拥有该互斥区)
      mHandle:=CreateMutex(nil,True,PChar(Project));
      if GetLastError=ERROR_ALREADY_EXISTS then
       //该互斥区已存在则表明已有本程序的另一个实例在运行
        begin
          ShowMessage('已经有该程序在运行');
          //保存程序标题
          AppName:=Application.Title;
          //不显示本窗口
          Application.ShowMainForm:=False;
          //改变程序标题,以使函数FindWindow找到的是前一个实例窗口
          Application.Title:='destroy me';
          //寻找前一个实例窗口句柄
          PreviousInstanceWindow:=FindWindow(nil,PChar(AppName));
          //已经找到
          if PreviousInstanceWindow<>0 then
          //如果该窗口最小化则恢复
             if IsIconic(PreviousInstanceWindow) then
               ShowWindow(PreviousInstanceWindow,SW_RESTORE)
            else
            //如果程序在后台则将其放到前台
             SetForegroundWindow(PreviousInstanceWindow);
             //中止本实例
            Application.Terminate;
          end;
        finalization
        //该互斥区对象仍存在则关闭对象
          if mHandle<>0 then
            CloseHandle(mHandle);
    end.
      

  4.   

    在主窗口的OnCreate事件里写;
    var h:THandle;
    h:=FindWindow(nil,'你的程序标题!');
    if h<>0 then
    begin
       SendMessage(h,WM_SYSCOMMAND,SC_MAXIMIZE,0);//让你的已经打开的程序最大化
       Application.Terminate;//结束程序
    end;
      

  5.   

    http://community.csdn.net/Expert/topic/3626/3626563.xml?temp=7.511538E-02
    里面我的回答
      

  6.   

    CreateMutex(nil, false, 一个字符串);
    if GetLastError=ERROR_ALREADY_EXISTS then
    begin
      Application.MessageBox('该程序只能运行一个实例','提示',MB_OK OR MB_ICONINFORMATION); 
      Application.Terminate;
    end;