Lobo
Lobo

Reputation: 4157

Bring window to front from Java

Is there any way to bring a window to the front using Java? Maybe using some operating system library?

Upvotes: 5

Views: 4830

Answers (3)

Gal Levy
Gal Levy

Reputation: 39

package focus;

import com.sun.jna.Native;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.win32.StdCallLibrary;

public class ForegroundWindow {
	private interface User32 extends StdCallLibrary {
		final User32 instance = (User32) Native.loadLibrary("user32", User32.class);

		boolean SetForegroundWindow(HWND handle);

		HWND FindWindowA(String className, String windowName);

		HWND GetForegroundWindow();
	}

	private String getWindowName(String winName) {
		String winText = "";
		if (winText.contains(winName)) {
			return winText;
		}
		return null;
	}

	public boolean bringWindowToFront(String className, String winName) {
		HWND hWnd = User32.instance.FindWindowA(className, getWindowName(winName));
		if (hWnd == null) {
			return false;
		}
		return User32.instance.SetForegroundWindow(hWnd);
	}
}

Upvotes: 2

Tag
Tag

Reputation: 296

SWT is nice for Win32 calls.

import org.eclipse.swt.internal.win32.OS;

@SuppressWarnings("restriction")

int hwnd = OS.FindWindowW(null, "Titlein".toCharArray());

Upvotes: 0

Favonius
Favonius

Reputation: 13984

It seems it is possible, but then your solution would be very OS specific.

Theoretically it can be done by placing a call to win32 API in the following sequence:

  1. FindWindow Function
  2. ShowWindow Function OR,
  3. BringWindowToTop Function

Now the problem comes 'how to call them from java?'. Well all the above functions are defined in user32.dll and it can be accessed by JNA.

Some sample references to user32 API using JNA are:

  1. How can I read the window title with JNI or JNA?
  2. call FindWindow method of User32.dll using java

Use google to find more.

Hope this will help.

Upvotes: 4

Related Questions