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

前端 未结 17 2595
甜味超标
甜味超标 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:01

    In Java, using JNA with the Kernel32.dll library, similar to a C++ solution. Runs the CtrlCSender main method as a Process which just gets the console of the process to send the Ctrl+C event to and generates the event. As it runs separately without a console the Ctrl+C event does not need to be disabled and enabled again.

    CtrlCSender.java - Based on Nemo1024's and KindDragon's answers.

    Given a known process ID, this consoless application will attach the console of targeted process and generate a CTRL+C Event on it.

    import com.sun.jna.platform.win32.Kernel32;    
    
    public class CtrlCSender {
    
        public static void main(String args[]) {
            int processId = Integer.parseInt(args[0]);
            Kernel32.INSTANCE.AttachConsole(processId);
            Kernel32.INSTANCE.GenerateConsoleCtrlEvent(Kernel32.CTRL_C_EVENT, 0);
        }
    }
    

    Main Application - Runs CtrlCSender as a separate consoless process

    ProcessBuilder pb = new ProcessBuilder();
    pb.command("javaw", "-cp", System.getProperty("java.class.path", "."), CtrlCSender.class.getName(), processId);
    pb.redirectErrorStream();
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);
    Process ctrlCProcess = pb.start();
    ctrlCProcess.waitFor();
    

提交回复
热议问题