我利用 Winexec('rksp_P',sw_show); 调用一个程序,如果这个程序已经运行,我如何做到不能再次运行这个程序?

解决方案 »

  1.   

    防止程序的多次运行    
      互斥对象(CreateMutex)应该是最好的方法 
    //项目文件...beginApplication.initialation;if CreateMutex then beginApplication.CreateForm(Form1, TForm1);Application.Run;end elseDestroyMutex;end;//主窗体文件...implementationvarMutex: hWnd;function CreateMutex: Boolean;varPrevInstHandle: THandle;AppTitle: PChar;beginAppTitle := StrAlloc(100);StrPCopy(AppTitle, Application.Title);Result := True;Mutex := Windows.CreateMutex(nil, False, AppTitle);if (GetLastError = ERROR_ALREADY_EXISTS) or (Mutex = 0) then beginResult := False;SetWindowText(Application.Handle, '');PrevInstHandle := FindWindow(nil, AppTitle);if PrevInstHandle <> 0 then beginif IsIconic(PrevInstHandle) thenShowWindow(PrevInstHandle, SW_RESTORE)elseBringWindowToTop(PrevInstHandle);SetForegroundWindow(PrevInstHandle);end;if Mutex <> 0 thenMutex := 0;end;StrDispose(AppTitle);end;procedure DestroyMutex;beginif Mutex <> 0 thenCloseHandle(Mutex);end; 
     
       
      

  2.   

    var 
      Hwnd:Thandle;
    begin
      Hwnd:=findWindow('Tform1','One Copy');
      if Hwnd=0 then
        begin
          application.Initialize;
          application.CreatForm(Tform1,Form1);
          application.Run;
        end
      else
        begin
          if not IsWindowVisible(Hwnd) then
            postMessage(Hwnd,Wm_User,0,0);
          SetForegroundWindow(Hwnd);
        end;
    end;
     
      PostMessage API函数向目标应用程序窗口的消息队列发送了一个消息
    由第一个参数表示。在窗体的代码中,可以添加特殊函数来处理该消息:
      public
        procedure WMUser(var msg:TMessage);
      在代码的实现部分:
      procedure Tform1.WMUser(var msg:tMessage);
        begin
          application.Restore;
        end;注意:
      该方法将会在应用程序初始化前检查是否该应用程序已经在运行,若是
    则不会再次运行,并激活已运行的程序。
      但是,如果我们在DELPHI IDE中运行该程序,它可能不会正常工作,因
    为FindWindow调用可能会返回一个已经存在的窗口:设计时的窗口。这样
    程序将一次也不会运行,除非我们关闭设计窗口及其源代码,或关闭该项目
    而在WINDOWS EXPLORER中运行程序。
      

  3.   

    softheaded(傻呆) :
    别急,慢慢看就明白了,在执行这个程序前加入如下语句:
    handle:=findwindow('tform1',nil);
      if handle<>0 then
      begin
        messagebox(0,'该程序已经有一个在运行中!','错误',0);
        halt;
      end;
      

  4.   

    最简单的办法是; 把你调用的哪个程序写成单实例运行啊,就可以了,如果真的你自己不能用api函数解决掉
    就用一个控件就好了,套件LMD里有一个叫One instance的,你直接拖到程序窗体上就可以了,保证单实例运行!呵呵