读书人

delphi 杀掉exe程序解决办法

发布时间: 2013-01-11 11:57:35 作者: rapoo

delphi 杀掉exe程序
我有一个delphi的exe程序 demo.exe


我不想让这个程式双开,当第二个demo.exe运行时,想把第一个杀掉


这个怎样实现阿

我加上下面代码,会把它自己杀掉。。。。



if not ProcedureIsExists('demo.exe') then //进程不存在则打开它
begin
ShellExecute(handle,'open','\\url\demo.exe','','',SW_SHOW);
end
else
begin
WinExec('cmd /C '+'taskkill /f /im demo.exe',0);
delay(1000);
ShellExecute(handle,'open','\\url\demo.exe','','',SW_SHOW);
end;


[解决办法]
var
hw : HWND;
gt : Integer;
begin
Application.Initialize;
Application.Title := 'runmyfile';
hw := CreateMutex(nil,False,'runmyfile'); {创建互斥体对象}
gt := GetLastError;
if gt <> Error_ALREADY_EXISTS then {如果没有发现互斥体对象}
begin
Application.CreateForm(TForm1,Form1); {创建窗体}
Application.Run;
end
else
begin
Application.MessageBox('程序已经运行','提示',MB_OK);
Application.Terminate;
ReleaseMutex(hw);{释放互斥体}
end;
end;

[解决办法]
program XdeltaGui;

uses
Windows, Forms, SysConst,
XdeltaGui0 in 'XdeltaGui0.pas' {FrmMain};

{$R *.res}
var
Hwnd: THandle;
begin
Application.Initialize;
CreateMutex(nil, False, 'FrmMain');
if GetLastError = ERROR_ALREADY_EXISTS then
begin
Hwnd := FindWindow('TfrmMain', 'xdeltaGUI');
if Hwnd <> 0 then
begin
SetWindowPos(hwnd, Hwnd_Topmost, 274, 206, 451, 319, 0); //274, 206, 451, 319, 0
SetWindowPos(Hwnd, Hwnd_notopmost, 274, 206, 451, 319, 0);
ShowWindow(HWnd, SW_SHOW);
Halt(0);
end;
end;
Application.Title := 'xdeltaGUI';
Application.CreateForm(TFrmMain, FrmMain);
Application.Run;
end.


[解决办法]
楼上直接用halt(0)不安全吧。。应该先Application.Terminate;
[解决办法]
建一个单元unit2;

unit Unit2;

interface

uses
Forms, Windows, Messages;

var _HMutex:hwnd;



procedure KillSelf();

implementation

procedure KillSelf();
var
H:HWND;
begin
if OpenMutex(MUTEX_ALL_ACCESS,False,PChar(Application.Title))<>0 then
begin
{关闭前者,或者自己退出用halt或用Application.Terminate}
H:=FindWindow(nil,'Form1');
if H<>0 then
PostMessage(H,WM_Close,0,0);
end;

//创建互斥
_HMutex := CreateMutex(nil, False, PChar(Application.Title));
end;

end.

{在program工程文件调用:}
Application.Initialize;
KillSelf();
...

{在程序关闭时加上,比如在主窗体Close事件:}
ReleaseMutex(_HMutex);

读书人网 >.NET

热点推荐