code_junkie

Delphi - Gracefully Closing Created Process in Service. (using tprocess / createProcess)

Nov 12th, 2011
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. if CreateProcess( nil , PChar( FProcess.Command ) , nil , nil , False ,
  2. NORMAL_PRIORITY_CLASS , nil , Directory ,
  3. StartupInfo , ProcessInfo ) then
  4. begin
  5. if FProcess.Wait then
  6. begin
  7. WaitForSingleObject( ProcessInfo.hProcess , Infinite );
  8. GetExitCodeProcess( ProcessInfo.hProcess , ExitCode );
  9. if Assigned( FProcess.FOnFinished ) then
  10. FProcess.FOnFinished( FProcess , ExitCode );
  11. end;
  12. CloseHandle( ProcessInfo.hProcess );
  13. CloseHandle( ProcessInfo.hThread );
  14. end;
  15.  
  16. uses Windows;
  17.  
  18. interface
  19.  
  20. function MyTerminateAppEnum(hHwnd:HWND; dwData:LPARAM):Boolean; stdcall;
  21.  
  22. implementation
  23.  
  24. function MyTerminateAppEnum(hHwnd:HWND; dwData:LPARAM):Boolean;
  25. var
  26. vID:DWORD;
  27. begin
  28. GetWindowThreadProcessID(hHwnd, @vID);
  29. if vID = dwData then
  30. begin
  31. PostMessage(hHwnd, WM_CLOSE, 0, 0); //tell window to close gracefully
  32. Result := False; //can stop enumerating
  33. end
  34. else
  35. begin
  36. Result := TRUE; //keep enumerating until you find your id
  37. end;
  38. end;
  39.  
  40. Procedure TerminateMe(YourSavedProcessInfo:TProcessInformation);
  41. var
  42. vExitCode:UINT;
  43. begin
  44. GetExitCodeProcess(YourSavedProcessInfo.hProcess, vExitCode);
  45. if (vExitCode = STILL_ACTIVE) then //launched app still running..
  46. begin
  47. //tell it to close
  48. EnumWindows(@MyTerminateAppEnum, YourSavedProcessInfo.dwProcessId);
  49.  
  50. if WaitForSingleObject(YourSavedProcessInfo.hProcess, TIMEOUT_VAL) <> WAIT_OBJECT_0 then
  51. begin
  52. if not TerminateProcess(YourSavedProcessInfo.hProcess, 0) then //didn't close, try to terminate
  53. begin
  54. //uh-oh Didn't close, didn't terminate..
  55. end;
  56. end;
  57. end;
  58. CloseHandle(YourSavedProcessInfo.hProcess);
  59. CloseHandle(YourSavedProcessInfo.hThread);
  60. end;
Add Comment
Please, Sign In to add comment