Program.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.Runtime.InteropServices;
  2. namespace SendCtrlC
  3. {
  4. internal static class Program
  5. {
  6. [DllImport("kernel32.dll", SetLastError = true)]
  7. private static extern bool AttachConsole(uint dwProcessId);
  8. [DllImport("kernel32.dll", SetLastError = true)]
  9. private static extern bool GenerateConsoleCtrlEvent(uint dwCtrlEvent, uint dwProcessGroupId);
  10. [DllImport("kernel32.dll")]
  11. private static extern bool FreeConsole();
  12. [DllImport("kernel32.dll")]
  13. private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate? handlerRoutine, bool add);
  14. private delegate bool ConsoleCtrlDelegate(uint ctrlType);
  15. private const uint CTRL_C_EVENT = 0;
  16. private enum ExitCode
  17. {
  18. Success = 0,
  19. InvalidArgument = 1,
  20. AttachConsoleFailed = 2,
  21. GenerateCtrlEventFailed = 3
  22. }
  23. private static int Main(string[] args)
  24. {
  25. if (args.Length != 1)
  26. {
  27. return (int)ExitCode.InvalidArgument;
  28. }
  29. if (!uint.TryParse(args[0], out uint processId))
  30. {
  31. return (int)ExitCode.InvalidArgument;
  32. }
  33. // 尝试附加到指定进程的控制台
  34. if (!AttachConsole(processId))
  35. {
  36. return (int)ExitCode.AttachConsoleFailed;
  37. }
  38. // 设置控制处理程序以避免自己进程接收到信号
  39. SetConsoleCtrlHandler(null, true);
  40. // 发送CTRL_C_EVENT
  41. if (!GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0))
  42. {
  43. return (int)ExitCode.GenerateCtrlEventFailed;
  44. }
  45. // 释放控制台
  46. FreeConsole();
  47. // 如果没有异常发生,退出代码为Success
  48. return (int)ExitCode.Success;
  49. }
  50. }
  51. }