1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- using System.Runtime.InteropServices;
- namespace SendCtrlC
- {
- internal static class Program
- {
- [DllImport("kernel32.dll", SetLastError = true)]
- private static extern bool AttachConsole(uint dwProcessId);
- [DllImport("kernel32.dll", SetLastError = true)]
- private static extern bool GenerateConsoleCtrlEvent(uint dwCtrlEvent, uint dwProcessGroupId);
- [DllImport("kernel32.dll")]
- private static extern bool FreeConsole();
- [DllImport("kernel32.dll")]
- private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate? handlerRoutine, bool add);
- private delegate bool ConsoleCtrlDelegate(uint ctrlType);
- private const uint CTRL_C_EVENT = 0;
- private enum ExitCode
- {
- Success = 0,
- InvalidArgument = 1,
- AttachConsoleFailed = 2,
- GenerateCtrlEventFailed = 3
- }
- private static int Main(string[] args)
- {
- if (args.Length != 1)
- {
- return (int)ExitCode.InvalidArgument;
- }
- if (!uint.TryParse(args[0], out uint processId))
- {
- return (int)ExitCode.InvalidArgument;
- }
- // 尝试附加到指定进程的控制台
- if (!AttachConsole(processId))
- {
- return (int)ExitCode.AttachConsoleFailed;
- }
- // 设置控制处理程序以避免自己进程接收到信号
- SetConsoleCtrlHandler(null, true);
- // 发送CTRL_C_EVENT
- if (!GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0))
- {
- return (int)ExitCode.GenerateCtrlEventFailed;
- }
- // 释放控制台
- FreeConsole();
- // 如果没有异常发生,退出代码为Success
- return (int)ExitCode.Success;
- }
- }
- }
|