Windows – Focus and close application by ID

cmd.exewindows

In Windows if I have the PID for an application and I want to either focus or close the app via the command prompt.

What commands do I need to run?

e.g.

FOCUS 123

or

CLOSE 123

Where 123 is the PID.

Best Answer

To kill an app instance using its PID, use taskkill /pid <pid> (tasklist will list all the running processes).

To switch focus to an app instance using its PID, use the VBScript below:

set objShell = WScript.CreateObject("WScript.Shell")
objShell.AppActivate WScript.Arguments.Item(0)
objShell.SendKeys "% x"

The MSDN documentation says that % represents ALT. Together with SPACE we can access the Alt-Space popup menu, and use an keyboard accelerator to maximize or restore the window.

If you save it as Focus.vbs, you can invoke it from the command line using:

wscript Focus.vbs <pid>
Related Question