How to determine if a screensaver is running in Java?

本秂侑毒 提交于 2019-11-27 15:56:15

Try using the JNA library to invoke the SystemParametersInfo system call.

The following example uses code from the win32 examples provided by JNA:

public class JNATest {

    public static void main(String[] args) {
        W32API.UINT_PTR uiAction = new W32API.UINT_PTR(User32.SPI_GETSCREENSAVERRUNNING);
        W32API.UINT_PTR uiParam = new W32API.UINT_PTR(0);
        W32API.UINT_PTR fWinIni = new W32API.UINT_PTR(0);
        PointerByReference pointer = new PointerByReference();

        User32.INSTANCE.SystemParametersInfo(uiAction, uiParam, pointer, fWinIni);

        boolean running = pointer.getPointer().getByte(0) == 1;

        System.out.println("Screen saver running: "+running);
    }
}


public interface User32 extends W32API {

    User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class, DEFAULT_OPTIONS);

    long SPI_GETSCREENSAVERRUNNING = 0x0072;

    boolean SystemParametersInfo(
        UINT_PTR uiAction,
        UINT_PTR uiParam,
        PointerByReference pvParam,
        UINT_PTR fWinIni
      );


}

Well, this is absolutely not clean, but it works as a dirty workaround:

I checks if 'any' screensaver (which have .SCR suffix) is running.

  private static boolean isScreensaverRunning() {
    List<String> p = WindowsUtils.listRunningProcesses();
    for (String s : p) {
      if (s.endsWith(".SCR")) {
    return true;
      }
    }
    return false;
  }

  public static List<String> listRunningProcesses() {
    List<String> processes = new ArrayList<String>();
    try {
      String line;
      Process p = Runtime.getRuntime().exec("tasklist.exe /fo csv /nh");
      BufferedReader input = new BufferedReader
      (new InputStreamReader(p.getInputStream()));
      while ((line = input.readLine()) != null) {
      if (!line.trim().equals("")) {
          // keep only the process name
          line = line.substring(1);
      processes.add(line.substring(0, line.indexOf("\"")));
      }

      }
      input.close();
    }
    catch (Exception err) {
      err.printStackTrace();
    }
    return processes;
  }

Source of listRunningProcesses: http://www.rgagnon.com/javadetails/java-0593.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!