WindowsProcessManager.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using MediaBrowser.Controller.Diagnostics;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Runtime.InteropServices;
  5. namespace MediaBrowser.ServerApplication.Native
  6. {
  7. public class WindowsProcessManager : IProcessManager
  8. {
  9. public void SuspendProcess(Process process)
  10. {
  11. process.Suspend();
  12. }
  13. public void ResumeProcess(Process process)
  14. {
  15. process.Resume();
  16. }
  17. public bool SupportsSuspension
  18. {
  19. get { return true; }
  20. }
  21. }
  22. public static class ProcessExtension
  23. {
  24. [DllImport("kernel32.dll")]
  25. static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
  26. [DllImport("kernel32.dll")]
  27. static extern uint SuspendThread(IntPtr hThread);
  28. [DllImport("kernel32.dll")]
  29. static extern int ResumeThread(IntPtr hThread);
  30. public static void Suspend(this Process process)
  31. {
  32. foreach (ProcessThread thread in process.Threads)
  33. {
  34. var pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)thread.Id);
  35. if (pOpenThread == IntPtr.Zero)
  36. {
  37. break;
  38. }
  39. SuspendThread(pOpenThread);
  40. }
  41. }
  42. public static void Resume(this Process process)
  43. {
  44. foreach (ProcessThread thread in process.Threads)
  45. {
  46. var pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)thread.Id);
  47. if (pOpenThread == IntPtr.Zero)
  48. {
  49. break;
  50. }
  51. ResumeThread(pOpenThread);
  52. }
  53. }
  54. public static void Print(this Process process)
  55. {
  56. Console.WriteLine("{0,8} {1}", process.Id, process.ProcessName);
  57. }
  58. }
  59. [Flags]
  60. public enum ThreadAccess : int
  61. {
  62. TERMINATE = (0x0001),
  63. SUSPEND_RESUME = (0x0002),
  64. GET_CONTEXT = (0x0008),
  65. SET_CONTEXT = (0x0010),
  66. SET_INFORMATION = (0x0020),
  67. QUERY_INFORMATION = (0x0040),
  68. SET_THREAD_TOKEN = (0x0080),
  69. IMPERSONATE = (0x0100),
  70. DIRECT_IMPERSONATION = (0x0200)
  71. }
  72. }