Using JNA to get/set application identifier

前端 未结 3 1152
忘了有多久
忘了有多久 2020-12-04 12:48

Following up on my previous question concerning the Windows 7 taskbar, I would like to diagnose why Windows isn\'t acknowledging that my application is independent of

3条回答
  •  旧时难觅i
    2020-12-04 13:15

    I didn't see your question before otherwise I would have given a try even without a bounty.

    Here is what I came up with. Please note, as stated in the code itself, I didn't implement proper memory clean up with the CoTaskMemFree function (from Ole32.dll). So I suggest you take only the implementation for SetCurrentProcessExplicitAppUserModelID()

    package com.stackoverflow.AppIdTest;
    
    import com.sun.jna.Native;
    import com.sun.jna.NativeLong;
    import com.sun.jna.Pointer;
    import com.sun.jna.WString;
    import com.sun.jna.ptr.PointerByReference;
    
    public class AppIdTest
    {
    
      public static void main(String[] args) throws Exception
      {
        setCurrentProcessExplicitAppUserModelID(AppIdTest.class.getName());
    
        System.out.println(getCurrentProcessExplicitAppUserModelID());
      }
    
      // DO NOT DO THIS, IT'S JUST FOR TESTING PURPOSE AS I'M NOT FREEING THE MEMORY
      // AS REQUESTED BY THE DOCUMENTATION:
      //
      // http://msdn.microsoft.com/en-us/library/dd378419%28VS.85%29.aspx
      //
      // "The caller is responsible for freeing this string with CoTaskMemFree when
      // it is no longer needed"
      public static String getCurrentProcessExplicitAppUserModelID()
      {
        final PointerByReference r = new PointerByReference();
    
        if (GetCurrentProcessExplicitAppUserModelID(r).longValue() == 0)
        {
          final Pointer p = r.getValue();
    
    
          return p.getString(0, true); // here we leak native memory by lazyness
        }      
        return "N/A";
      }
    
      public static void setCurrentProcessExplicitAppUserModelID(final String appID)
      {
        if (SetCurrentProcessExplicitAppUserModelID(new WString(appID)).longValue() != 0)
          throw new RuntimeException("unable to set current process explicit AppUserModelID to: " + appID);
      }
    
      private static native NativeLong GetCurrentProcessExplicitAppUserModelID(PointerByReference appID);
      private static native NativeLong SetCurrentProcessExplicitAppUserModelID(WString appID);
    
    
      static
      {
        Native.register("shell32");
      }
    }
    

    Does it work for you?

    At least here it correctly prints back:

    com.stackoverflow.AppIdTest.AppIdTest

提交回复
热议问题