為何在線程中無法關閉程序? ( 积分: 50 )

  • 主题发起人 主题发起人 takdick
  • 开始时间 开始时间
T

takdick

Unregistered / Unconfirmed
GUEST, unregistred user!
procedure&nbsp;thread1;<br>begin<br>...<br>.......<br>if&nbsp;close=true&nbsp;then&nbsp;&nbsp;//當close為true時<br>begin<br>winexec(pchar(application.exename),sw_normal);&nbsp;//重啟自身程序<br>application.Terminate;&nbsp;&nbsp;//退出程序&nbsp;&nbsp;//這一動作失效,程序沒有退出<br>end;<br>end;<br><br>h:=beginthread(nil,0,@thread1,nil,0,hid);
 
其实已经关闭了<br>因为你用winexec又启动了一次该程序<br>把下面的加上再试下<br>program&nbsp;Project1;<br><br>uses<br>&nbsp;&nbsp;Forms,windows,<br>&nbsp;&nbsp;Unit1&nbsp;in&nbsp;'Unit1.pas'&nbsp;{Form1};<br><br>{$R&nbsp;*.res}<br>var<br>&nbsp;&nbsp;mutex:&nbsp;HWND;<br>&nbsp;&nbsp;error:&nbsp;integer;<br>begin<br>&nbsp;&nbsp;Application.Initialize;<br><br>&nbsp;&nbsp;mutex:=&nbsp;CreateMutex(nil,false,'xxxx');<br>&nbsp;&nbsp;error:=&nbsp;GetLastError;<br>&nbsp;&nbsp;if&nbsp;error&nbsp;&lt;&gt;&nbsp;ERROR_ALREADY_EXISTS&nbsp;then<br>&nbsp;&nbsp;begin<br>&nbsp;&nbsp;&nbsp;&nbsp;Application.CreateForm(TForm1,&nbsp;Form1);<br>&nbsp;&nbsp;&nbsp;&nbsp;Application.Run;<br>&nbsp;&nbsp;end;<br>&nbsp;&nbsp;ReleaseMutex(mutex);<br>end.
 
我的程序有使用窗體,重啟自身程序後任務欄就多出一個同樣的程序.<br>而且我試去掉winexec(pchar(application.exename),sw_normal);這一動作,程序也沒有關閉.
 
這不難吧,怎麼沒人回答.<br>煩請指教,謝謝.
 
是线程哦,<br>一般来说不在子线程中直接关闭主线程,而是通过间接方法.<br>子线程里结束主线程的方法很多,直接向主线程发消息,比较好的是在子线程退出时返回一个退出码(无论是DELPHI的TThead封装还是WindowsAPI都有线程退出码),如果是某个特定值,主线程就结束。<br>procedure&nbsp;TForm1.Button1Click(Sender:&nbsp;TObject);<br>&nbsp;&nbsp;procedure&nbsp;MyThread;stdcall;<br>&nbsp;&nbsp;begin<br>&nbsp;&nbsp;&nbsp;&nbsp;form1.Caption:=&nbsp;'xxx';<br>&nbsp;&nbsp;end;<br>var<br>&nbsp;&nbsp;threadID:&nbsp;Cardinal;<br>begin<br>&nbsp;&nbsp;if&nbsp;&nbsp;CreateThread(nil,0,@MyThread,nil,0,threadID)&lt;&gt;&nbsp;0&nbsp;then<br>&nbsp;&nbsp;begin<br>&nbsp;&nbsp;&nbsp;&nbsp;sleep(100);<br>&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;Self.Caption&nbsp;=&nbsp;'xxx'&nbsp;then<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Application.Terminate;<br>&nbsp;&nbsp;end;<br>end;
 
接受答案了.
 
后退
顶部