import com.sun.jna.Native;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import javax.swing.*;
import java.awt.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class FocusApp {
private static int switchCount = 0;
private static String lastWindow = "";
private static long lastSwitchTime = System.currentTimeMillis();
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Window Switch Logger");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
JTextArea logArea = new JTextArea();
logArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(logArea);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setVisible(true);
new Thread(() -> monitorWindowFocus(logArea)).start();
});
}
private static void monitorWindowFocus(JTextArea logArea) {
User32 user32 = User32.INSTANCE;
WinDef.HWND hwnd = user32.GetForegroundWindow();
char[] windowText = new char[512];
user32.GetWindowText(hwnd, windowText, 512);
lastWindow = Native.toString(windowText);
while (true) {
hwnd = user32.GetForegroundWindow();
user32.GetWindowText(hwnd, windowText, 512);
String currentWindow = Native.toString(windowText);
if (!currentWindow.equals(lastWindow)) {
long currentTime = System.currentTimeMillis();
long duration = currentTime - lastSwitchTime;
lastSwitchTime = currentTime;
String logMessage = String.format("Window: %s (Duration: %d ms)\n", lastWindow, duration);
lastWindow = currentWindow;
switchCount++;
logArea.append(logMessage);
System.out.print(logMessage);
try (BufferedWriter writer = new BufferedWriter(new FileWriter("window_switch_log.txt", true))) {
writer.write(logMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}