Share this page 

Detect if a program is running (JNA)Tag(s): JNI/JNA


JNA (Java Native Access) provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code - no JNI or native code is required.

In this HowTo, we detect if an instance of program is running or not. The following code checks if Excel is running. It Excel is running, we activate the window and bring it to the front.


import com.sun.jna.platform.win32.User32;

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 IsRunning {



	public static void main(String[] args) {

		HWND hwnd = User32.INSTANCE.FindWindow

		       (null, "Microsoft Excel - Classeur1"); // window title

		if (hwnd == null) {

			System.out.println("Excel is not running");

		}

		else{

			User32.INSTANCE.ShowWindow(hwnd, 9 );        // SW_RESTORE

			User32.INSTANCE.SetForegroundWindow(hwnd);   // bring to front

		}

	}

}

This technique looks for the window title. Since my Excel installation is in French then the default sheet name is Classeur1(in English it would be Sheet1).

Another way is to look for the window class name. For Excel, the class name is XLMAIN.

To search for the class name instead of the window title, change this line :


HWND hwnd = User32.INSTANCE.FindWindow("XLMAIN", null); // window class name

To determine the class name of a window for a specific program, you can use something like Spy++ (installed with Visual Studio) or the free alternative WinID.

It is also possible to search for the class name and the title to make the search more precise.

See also this Howto