Search code examples
javaswingprocessbuilder

Start/Stop Windows Service with buttons


I'm working on creating a very simple app to stop and start a windows service. I need it to have a GUI interface so I choose JAVA. If you know a simpler language let me know. As a sample I would like for it to stop and start print spooler. I've created the GUI interface using NetBeans, but I need help with the coding part. Please help. Thanks!

package MyServiceToolPKG;
public class MyServiceToolGUI extends javax.swing.JFrame {

/**
 * Creates new form MyServiceToolGUI
 */
public MyServiceToolGUI() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    StartButton = new javax.swing.JButton();
    StopButton = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    StartButton.setText("Start");
    StartButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            StartButtonActionPerformed(evt);
        }
    });

    StopButton.setText("Stop");
    StopButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            StopButtonActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(19, 19, 19)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(StopButton)
                .addComponent(StartButton))
            .addContainerGap(26, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(StartButton)
            .addGap(18, 18, 18)
            .addComponent(StopButton)
            .addContainerGap(22, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void StartButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
}                                           

private void StopButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
}                                          

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(MyServiceToolGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MyServiceToolGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MyServiceToolGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MyServiceToolGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MyServiceToolGUI().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton StartButton;
private javax.swing.JButton StopButton;
// End of variables declaration                   

}

Updated Code:

private void StartButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    StartSpooler();
}                                           

private void StopButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
    StopSpooler();
}
private void StopSpooler() {
    String[] args = {"stop"};
    String[] command = {"cmd.exe", "/c", "sc", args[0], "spooler"};
    try {
      Process process = new ProcessBuilder(command).start();
      InputStream inputStream = process.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String line;
      while ((line = bufferedReader.readLine()) != null) {
         System.out.println(line);
      }
    } catch(Exception ex) {
      System.out.println("Exception : "+ex);
    }
}

private void StartSpooler() {
    String[] args = {"start"};
    String[] command = {"cmd.exe", "/c", "sc", args[0], "spooler"};
    try {
      Process process = new ProcessBuilder(command).start();
      InputStream inputStream = process.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String line;
      while ((line = bufferedReader.readLine()) != null) {
         System.out.println(line);
      }
    } catch(Exception ex) {
      System.out.println("Exception : "+ex);
    }
}

Thanks everyone!

This is my code:

private void StopSpooler() {
    String[] args = {"stop"};
    String[] command = {"cmd.exe", "/c", "sc", args[0], "spooler"};
    try {
      Process process = new ProcessBuilder(command).start();
      InputStream inputStream = process.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String line;
      while ((line = bufferedReader.readLine()) != null) {
         System.out.println(line);
      }
    } catch(Exception ex) {
      System.out.println("Exception : "+ex);
    }
}

private void StartSpooler() {
    String[] args = {"start"};
    String[] command = {"cmd.exe", "/c", "sc", args[0], "spooler"};
    try {
      Process process = new ProcessBuilder(command).start();
      InputStream inputStream = process.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
      String line;
      while ((line = bufferedReader.readLine()) != null) {
         System.out.println(line);
      }
    } catch(Exception ex) {
      System.out.println("Exception : "+ex);
    }
}

And I created a batch file I run as admin an calls the jar app

@echo off
java.exe -jar C:\test\MyServiceTool.jar
pause

Solution

  • In Windows Command Line: You need Administrator rights to do so. To stop a windows service:

    net stop Spooler
    

    To start a windows service:

    net start Spooler
    

    In Java you can execute a dos command with:

    try {
            Runtime.getRuntime().exec("net stop spooler");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }