Search code examples
javardp

Determine if Java App is being run over an RDP Session?


How can I detect if my Swing App is being run from a windows RDP session?

Java only solution preferred, but the app is guaranteed to be running on windows so I'm ok with shelling out.


Solution

  • I think you'll have to invoke the native Windows libraries to pull this off. Try something like this:

    import com.sun.jna.Library;
    import com.sun.jna.Native;
    import com.sun.jna.ptr.IntByReference;
    import com.sun.jna.win32.*; 
    import com.sun.jna.examples.win32.Kernel32;
    
    ...
    
    public static boolean isLocalSession() {
      Kernel32 kernel32;
      IntByReference pSessionId;
      int consoleSessionId;
      Kernel32 lib = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
      pSessionId = new IntByReference();
    
      if (lib.ProcessIdToSessionId(lib.GetCurrentProcessId(), pSessionId)) {
        consoleSessionId = lib.WTSGetActiveConsoleSessionId();
        return (consoleSessionId != 0xFFFFFFFF && consoleSessionId == pSessionId.getValue());
      } else return false;
    }
    

    That strange-looking condition for consoleSessionId is from the documentation for WTSGetActiveConsoleSessionId, which says:

    Return Value

    The session identifier of the session that is attached to the physical console. If there is no session attached to the physical console, (for example, if the physical console session is in the process of being attached or detached), this function returns 0xFFFFFFFF.