检查powerpoint是否已在Java中打开?

时间:2016-04-02 12:06:44

标签: java process runtime ms-office powerpoint

我想从Java代码中打开Microsoft powerpoint,但在此之前我想检查它是否已经打开,如果已打开则显示它,否则打​​开新的。

直到现在我写这个

Process p=Runtime.getRuntime().exec("cmd.exe /C start powerpnt");

这个命令每次都会打开新的电源点窗口,但我想显示已经打开过的电源窗口。

感谢

1 个答案:

答案 0 :(得分:1)

这里是检查进程是否已打开的完整代码 函数CheckApplicationIsOpen.isOpenApplication()返回状态'open'或'close' 在主要检查powerpoint exe是开始不使用任务管理器实例

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package checkapplicationisopen;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ANGEL
 */
public class CheckApplicationIsOpen {

    /**
     * @param args the command line arguments
     */


    /***
     * 
     * @param applicationName : whatever application you want to check if it is already open or not
     * @return the result status if it is open then 'open', otherwise 'close' 
     */
    public static String isOpenApplication(String applicationName)
    {
        String result="";
        try {
            String line;
            String pidInfo ="";

            Process p =Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe");

            BufferedReader input =  new BufferedReader(new InputStreamReader(p.getInputStream()));

            while ((line = input.readLine()) != null) {
                pidInfo+=line+"\n";
            }
            System.out.println("Data : "+pidInfo);
            input.close();

            if(pidInfo.contains(applicationName))
            {
               System.out.println(applicationName+"is open");
               result="open";
            }
            else
            {
                System.out.println("PowerPoint is Not Open");
                result="close";
                //

            }

        } catch (IOException ex) {
            Logger.getLogger(CheckApplicationIsOpen.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public static void main(String[] args) {

        try
        {
            if(!CheckApplicationIsOpen.isOpenApplication("POWERPNT.EXE").equals("open"))
            {
                Process p1=Runtime.getRuntime().exec("cmd.exe /C start powerpnt");
            }else
            {
                System.out.println("Application is Open");
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}