Close an external windows program using JNA Tag(s): JNA


This example will close a running Powerpoint. The idea is to scan the Windows titles and find a match. If found then the Windows message WinUser.WM_CLOSE is sent to the process using its handle.
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinUser;
import com.sun.jna.platform.win32.WinDef.HWND;

// https://github.com/twall/jna#readme
//    you need 2 jars : jna-3.5.1.jar and platform-3.5.1.jar

public class KillMyPP {
  public static void main(String[] args) {
     HWND hwnd = User32.INSTANCE.FindWindow
       (null, "Microsoft PowerPoint - [Présentation1]"); // window title
                                                         // you need to modify this
                                                         // for your need
     if (hwnd == null) {
       System.out.println("PPT is not running");
     }
     else{
       User32.INSTANCE.PostMessage(hwnd, WinUser.WM_CLOSE, null, null);  // can be WM_QUIT in some occasion
     }
  }
}
You can make the search more precise by specifying the class name as the first parameter. You find the class name of a specific Windows program with a special utility program like Spy++ or the free alternative WinID. For PowerPoint, the class name is PP12FrameClass.
        HWND hwnd = User32.INSTANCE.FindWindow
             ("PP12FrameClass", "Microsoft PowerPoint - [Présentation1]"); // class name and window title
You can search by the Windows title only, the class name only or with both.

To close Notepad

        HWND hwnd = User32.INSTANCE.FindWindow
             ("Notepad", null); // class name
        ...
        User32.INSTANCE.PostMessage(hwnd, WinUser.WM_CLOSE, null, null);
If there is a document to be saved you be prompted. To avoid that and discard the current document use the WM_QUIT message instead of WM_CLOSE.
        User32.INSTANCE.PostMessage(hwnd, WinUser.WM_QUIT, null, null);
If you want to kill all running instances, then you can loop until no handle is retrieved.
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinUser;
import com.sun.jna.platform.win32.WinDef.HWND;

// https://github.com/twall/jna#readme
//    you need 2 jars : jna-3.5.1.jar and platform-3.5.1.jar

public class KillAllNotepad {
  public static void main(String[] args) {
    for (;;) {
        HWND hwnd = User32.INSTANCE.FindWindow
          ("Notepad", null); // class name
        if (hwnd == null) {
           System.out.println("No Notepad instance detected");
           break;
        }
        else{
           System.out.println("Notepad instance found.");
           User32.INSTANCE.PostMessage(hwnd, WinUser.WM_QUIT, null, null);
        }
     }
  }
}

See also this Howto


blog comments powered by Disqus