随手写了一个简单的线程函数能实现你的要求, 不过没有判断出错与监视文件不存在的情况, 另外线程没有设置出口 [
][
][
][
], 不过我想你只要稍微改改就能用了。<br><br>调用方式: ExeMonitor('c:/xxx/aa.exe')即可。<br><br>uses<br> sysutils, windows, tlHelp32;<br><br>procedure MonitorThrd(const filename: string); stdcall;<br>var<br> h, h1: Cardinal;<br> pe: PROCESSENTRY32;<br> me: MODULEENTRY32;<br> Startup: _STARTUPINFOA;<br> PInfo: _PROCESS_INFORMATION;<br> s: string;<br> ps, fn: string;<br>label<br> l1;<br>begin<br> {分解文件名与路径}<br> fn := lowercase(extractfilename(filename));<br> ps := lowercase(extractfilepath(filename));<br> if ps[length(ps)]='/' then ps := copy(ps, 1, length(ps)-1);<br> PInfo.dwProcessId := 0;<br> {查询被监视程序是否已启动}<br> h := createtoolhelp32snapshot(TH32CS_SNAPPROCESS, 0);<br> pe.dwSize := sizeof(pe);<br> if process32first(h, pe) then<br> repeat<br> s := pe.szExeFile;<br> if lowercase(s)=fn then<br> begin<br> h1 := createtoolhelp32snapshot(TH32CS_SNAPMODULE, pe.th32ProcessID);<br> me.dwSize := sizeof(me);<br> if module32first(h1, me) then<br> repeat<br> s := me.szExePath;<br> if lowercase(s)=ps then<br> begin<br> PInfo.dwProcessId := pe.th32ProcessID;<br> goto l1;<br> end;<br> until not module32next(h1, me);<br> end;<br> until not process32next(h, pe);<br> closehandle(h);<br>l1:<br> {监控程序运行,如果关闭则自动重起}<br> while true do<br> begin<br> if pinfo.dwProcessId <> 0 then<br> pinfo.hProcess := openprocess(PROCESS_ALL_ACCESS, false, pinfo.dwProcessId)<br> else begin<br> fillchar(pinfo, sizeof(pinfo), 0);<br> fillchar(startup, sizeof(startup), 0);<br> startup.cb := sizeof(startup);<br> createprocess(pchar(filename), nil, nil, nil, false, 0, nil, pchar(ps), startup, pinfo);<br> end;<br> waitforsingleobject(pinfo.hProcess, INFINITE);<br> closehandle(pinfo.hProcess);<br> pinfo.dwProcessId := 0;<br> end;<br>end;<br><br>function ExeMonitor(FileName: string): Cardinal;<br>begin<br> {修改字符串引用计数,欺骗delphi,防止传递的参数FileName被自动释放}<br> if pinteger(integer(filename)-8)^ >= 0 then<br> inc(pinteger(integer(filename)-8)^);<br> {创建线程监视程序运行, 返回值为线程ThreadID, 你可以通过TerminateThread终止该线程}<br> closehandle(createthread(nil, 0, @MonitorThrd, pointer(FileName), 0, result));<br>end;<br><br>