java - 为什么我无法以这种方式关闭我的 JAR 可执行文件?

标签 java c# cmd process executable-jar

我编写了一个软件,需要我打开和关闭可执行 jar 文件。 目前我的代码能够使用特定参数打开 jar (我在代码示例中使用了记事本,因为我身上没有 Jar 文件或原始代码,并且需要测试我为此示例编写的内容是否有效) 我遇到的问题是,当我打开和关闭记事本时,我得到了正确的行为,但是当我尝试关闭 JAR 文件时,我没有得到响应。

我尝试过通过任务管理器下的进程名称来杀死 - 转到详细信息、应用程序名称以及 java、java.exe、javaw 等的变体。

这与通过 CMD 启动 jar 有关吗? 在这种情况下,我遇到了另一个问题,因为我有多个具有完全相同名称的进程,并且不确定当名称相同时如何获取 ID。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        // Click on the link below to continue learning how to build a desktop app using WinForms!
        System.Diagnostics.Process.Start("http://aka.ms/dotnet-get-started-desktop");

    }


    //string jarFile = "/JarLocation";
    //string jsonlocation = "/jsonlocation";
    //string command = $"java - jar {jarfile} -qsArgs {jsonLocation}";
    string command = "Notepad";
    string processName = "Notepad";
    List<int> processIDs = new List<int>();
    int[] processID;

    Thread testThread;
    ThreadStart ts;

    private void RunButton_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Running!");

        // METHOD 1     // Launch through CMD directly (in a new thread and try to terminate by process name)     
        /*
        new Thread(() =>
        {
            LaunchClient();
        }).Start();
        */


        // METHOD 2 // Generate 
        /*
        foreach (int ID in processIDs)
        {
            Console.WriteLine($"Process {ID} Created");
        }
        */

        //Method 3
        /*
        testThread = new Thread(new ThreadStart(LaunchClient()));
        //testThread.Start();
        */

        // Method 4
        ts = delegate { LaunchClient(); };



    }

    private void KillButton_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Killing!");
        try
        {
            // Method 1

            Process[] ProcList = Process.GetProcessesByName(processName);
            foreach (Process targetProc in ProcList)
            {
                targetProc.CloseMainWindow();
            }



            // Method 2
            /*
            foreach (int ID in processIDs)
            {
                Process killMe = Process.GetProcessById(ID);
                killMe.CloseMainWindow();
            }
            */

            // Method 3
            //testThread.Abort();

            //Method 4
            //ts.EndInvoke();

        }
        catch (Exception f)
        {
            Console.WriteLine("f.StackTrace");
        }
    }

    public void LaunchClient()
    {
        Thread.CurrentThread.IsBackground = false;
        Process proc = new Process();
        proc.StartInfo.FileName = "cmd.exe";
        proc.StartInfo.CreateNoWindow = true;
        proc.StartInfo.RedirectStandardInput = true;
        //proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.UseShellExecute = false;
        proc.Start();
        proc.StandardInput.WriteLine(command);
        proc.StandardInput.Flush();
        Console.WriteLine($"PROCESS ID: {proc.Id}");
        processIDs.Add(proc.Id);
        //proc.StandardInput.Close();
        proc.WaitForExit();
    }

}

很抱歉转储了大量代码,但我认为看到我对开始和结束的实现会有帮助。

编辑:

更新了给出的代码示例,以显示我尝试处理此问题的 4 种不同方法。

Method 1: 
Closing process by name (works for notepad, but not my jar)
2: Trying to pass the process ID back and use that to close the process 
(Cant see the ID outside of the thread running the cmd window)
3: using new threadstart (launchclient says 'method name expected')

4:  Doesn't open Notepad at all. 

最佳答案

如果您的 JAR 文件是用您的代码打开的,一个有用的技术是监听 windowClosing,当用户单击 Windows 上的 X 按钮(以及其他系统上的等效按钮)时会发生这种情况:

   addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
          System.exit(0);
      }
   });

关于java - 为什么我无法以这种方式关闭我的 JAR 可执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56074534/

相关文章:

java - SharedPreferences 和 TimePickerDialog

java - 是否有适合所有操作系统的 Swing JPanel 工具栏背景?

java - Maven 不生成目标测试类文件

c# - 创建者更新后无法注册 GattCharacteristicNotificationTrigger 后台任务

java - 在 Windows 中从命令行执行 java 程序失败

java - Spring 集成测试具有依赖注入(inject)的 Controller

c# - 比较属性的自定义错误消息不起作用

c# - 高性能网络应用的最佳实践

如果不提供 ".exe",Cmd 无法运行我的可执行文件

java - Java 问题和命令行错误