Can I send a ctrl-C (SIGINT) to an application on Windows?

前端 未结 17 2619
甜味超标
甜味超标 2020-11-22 09:15

I have (in the past) written cross-platform (Windows/Unix) applications which, when started from the command line, handled a user-typed Ctrl-C combinat

17条回答
  •  野性不改
    2020-11-22 10:02

    Thanks to jimhark's answer and other answers here, I found a way to do it in PowerShell:

    $ProcessID = 1234
    $MemberDefinition = '
        [DllImport("kernel32.dll")]public static extern bool FreeConsole();
        [DllImport("kernel32.dll")]public static extern bool AttachConsole(uint p);
        [DllImport("kernel32.dll")]public static extern bool GenerateConsoleCtrlEvent(uint e, uint p);
        public static void SendCtrlC(uint p) {
            FreeConsole();
            if (AttachConsole(p)) {
                GenerateConsoleCtrlEvent(0, p);
                FreeConsole();
            }
            AttachConsole(uint.MaxValue);
        }'
    Add-Type -Name 'dummyName' -Namespace 'dummyNamespace' -MemberDefinition $MemberDefinition
    [dummyNamespace.dummyName]::SendCtrlC($ProcessID) }
    
    

    What made things work was sending the GenerateConsoleCtrlEvent to the desired process group instead of all processes that share the console of the calling process and AttachConsole back to the console of the parent of the current process.

提交回复
热议问题