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
}
}
}
HWND hwnd = User32.INSTANCE.FindWindow
("PP12FrameClass", "Microsoft PowerPoint - [Présentation1]"); // class name and window title
To close Notepad
HWND hwnd = User32.INSTANCE.FindWindow
("Notepad", null); // class name
...
User32.INSTANCE.PostMessage(hwnd, WinUser.WM_CLOSE, null, null);
User32.INSTANCE.PostMessage(hwnd, WinUser.WM_QUIT, null, null);
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
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com