要在Windows上运行的Java服务中检测用户活动,可以使用以下方法:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
public class UserActivityDetector {
public static void main(String[] args) {
try {
Robot robot = new Robot();
robot.delay(5000); // 延迟5秒
while (true) {
robot.keyPress(KeyEvent.VK_WINDOWS); // 模拟按下Windows键
robot.keyRelease(KeyEvent.VK_WINDOWS); // 模拟松开Windows键
Thread.sleep(10000); // 等待10秒
}
} catch (AWTException | InterruptedException e) {
e.printStackTrace();
}
}
}
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class UserActivityDetector implements NativeKeyListener {
public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
GlobalScreen.addNativeKeyListener(new UserActivityDetector());
} catch (NativeHookException e) {
e.printStackTrace();
}
}
@Override
public void nativeKeyPressed(NativeKeyEvent e) {
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
}
@Override
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
}
@Override
public void nativeKeyTyped(NativeKeyEvent e) {
System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
}
}
这些方法可以帮助您检测用户在Windows系统上的活动。
领取专属 10元无门槛券
手把手带您无忧上云