J'essaie d'écrire un programme Java qui enregistre quelle application j'utilise toutes les 5 secondes (c'est une application de suivi temporel). J'ai besoin d'un moyen de savoir quelle est la fenêtre Active actuelle. J'ai trouvé Keyboardfocusmanager.getglobalactiveWindow () mais je ne peux pas le faire fonctionner correctement. Une solution de plate-forme croisée est préférable, mais si on n'existe pas, je développe que Linux avec X.org. Merci. P>
6 Réponses :
Pour trouver la fenêtre active (soyez une trame ou une boîte de dialogue) dans une application Java Swing, vous pouvez utiliser la méthode récursive suivante: ceci est de ici
Plus d'indices sur l'état de la fenêtre ici . P> P> P> P >
Cela ne prend que Java Windows en compte, alors que je pense que Steven veut obtenir la fenêtre active mondiale, que ce soit un programme Java ou non.
Oups! J'ai mal compris la question!
David a raison, je veux connaître le nom de la fenêtre globale active. De cette façon, je peux toujours garder une trace de lorsque j'utilise, disons, Firefox et quand j'utilise, disons, Eclipse.
Je suis tout à fait certain que vous trouverez qu'il n'y a aucun moyen d'énumérer les fenêtres actives dans Pure Java (j'ai eu l'air assez difficile auparavant), vous devez donc coder pour les plates-formes que vous souhaitez cibler. < / p>
sur Mac OS X, vous pouvez lancer un AppleScript en utilisant "OSASScript". P> LI>
sur x11, vous pouvez utiliser xwininfo . p> li>
sous Windows, vous pouvez probablement lancer des vbscript (par exemple, Ce lien semble prometteur). p> li> ul>
Si vous utilisez SWT, vous pourrez peut-être trouver des méthodes non-documentées et non publiques dans les Libs SWT, car SWT fournit des emballages pour beaucoup de l'OS API (par exemple, SWT sur Cocoa a le org .eclipse.swt.internal.cocoa.os # objc_msgsend () code> méthodes pouvant être utilisées pour accéder au système d'exploitation). Les classes "OS" équivalentes sur Windows et X11 peuvent avoir des API que vous pouvez utiliser. P>
J'ai écrit un script Bash qui enregistre la fenêtre Active actuelle: http://www.whitelamp.com/public/active-window-logger. HTML Il utilise une version patchée de WMCTRL mais fournit des détails sur une méthode alternative (plus lente) utilisant xProp et xwininfo. p>
Les liens vers le code Patch et le code source WMCTRL et le script peut être trouvé ci-dessus. p>
Merci beaucoup pour ce script.
J'ai écrit un programme Java à l'aide du script de User361601. J'espère que cela aidera les autres.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class WindowAndProcessInfo4Linux {
public static final String WIN_ID_CMD = "xprop -root | grep " + "\"_NET_ACTIVE_WINDOW(WINDOW)\"" + "|cut -d ' ' -f 5";
public static final String WIN_INFO_CMD_PREFIX = "xwininfo -id ";
public static final String WIN_INFO_CMD_MID = " |awk \'BEGIN {FS=\"\\\"\"}/xwininfo: Window id/{print $2}\' | sed \'s/-[^-]*$//g\'";
public String execShellCmd(String cmd){
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(new String[] { "/bin/bash", "-c", cmd });
int exitValue = process.waitFor();
System.out.println("exit value: " + exitValue);
BufferedReader buf = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
String output = "";
while ((line = buf.readLine()) != null) {
output = line;
}
return output;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
public String windowInfoCmd(String winId){
if(null!=winId && !"".equalsIgnoreCase(winId)){
return WIN_INFO_CMD_PREFIX+winId +WIN_INFO_CMD_MID;
}
return null;
}
public static void main (String [] args){
WindowAndProcessInfo4Linux windowAndProcessInfo4Linux = new WindowAndProcessInfo4Linux();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String winId = windowAndProcessInfo4Linux.execShellCmd(WIN_ID_CMD);
String winInfoMcd = windowAndProcessInfo4Linux.windowInfoCmd(winId);
String windowTitle = windowAndProcessInfo4Linux.execShellCmd(winInfoMcd);
System.out.println("window title is: "+ windowTitle);
}
}
J'ai créé ce AppleScript lors de la recherche de sujet similaire - celui-ci obtient la taille de la fenêtre spécifique
p>
global theSBounds
tell application "System Events"
set this_info to {}
set theSBounds to {}
repeat with theProcess in processes
if not background only of theProcess then
tell theProcess
set processName to name
set theWindows to windows
end tell
set windowsCount to count of theWindows
if processName contains "xxxxxxxx" then
set this_info to this_info & processName
else if processName is not "Finder" then
if windowsCount is greater than 0 then
repeat with theWindow in theWindows
tell theProcess
tell theWindow
if (value of attribute "AXTitle") contains "Genymotion for personal use -" then
-- set this_info to this_info & (value of attribute "AXTitle")
set the props to get the properties of the theWindow
set theSBounds to {size, position} of props
set this_info to this_info & theSBounds
end if
end tell
end tell
end repeat
end if
end if
end if
end repeat
end tell
return theSBoundsVeuillez également expliquer votre code au lieu de simplement en coller ici.
Utiliser SWT Internals, j'ai pu la mettre ensemble, et il semble fonctionner bien:
public static final void main(String[] args) {
try {
Thread.sleep(1000L);
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(getActiveWindowText());
}
Utilisez-vous un système de fenêtres comme KDE ou GNOME? Il peut être nécessaire de savoir que, car ce type de tâche doit généralement être effectué avec un code spécifique au système.