Search code examples
autocadautocad-pluginautolisp

How to check if application is running using AutoLISP


In CAD application (ZWCAD) I start my application by AutoLISP.

(startapp "C://[path]//Application.exe")

so the application runs each time new file is created. Works OK.

Now I want to limit instances of application just to one. So how can I check if the application is already running?


Solution

  • You could use a function to query the Win32_Process WMI class for a process with name matching your given application.

    Such a function might be written in the following way:

    ;; Win32 Process-p  -  Lee Mac
    ;; Returns T if a process exists with the supplied name
    
    (defun LM:win32process-p ( pro / qry rtn srv wmi )
        (if (setq wmi (vlax-create-object "wbemscripting.swbemlocator"))
            (progn
                (setq rtn
                    (vl-catch-all-apply
                       '(lambda ( )
                            (setq srv (vlax-invoke wmi 'connectserver)
                                  qry (vlax-invoke srv 'execquery (strcat "select * from win32_process where name = '" pro "'"))
                            )
                            (< 0 (vla-get-count qry))
                        )
                    )
                )
                (foreach obj (list qry srv wmi)
                    (if (= 'vla-object (type obj)) (vlax-release-object obj))
                )
                (and (not (vl-catch-all-error-p rtn)) rtn)
            )
        )
    )
    

    Which could be called in the following way:

    _$ (LM:win32process-p "notepad.exe")
    T