Application.advise() ComException in JNA

63 Views Asked by At

I'm handling Excel in Java. We are accessing Excel application data using JNA's COM API. I want to hook up when the Excel application closes. So, I'm using a JNA-based library.

your textcom.sun.jna.platform.win32.COM.util.Factory your texteu.doppel_helix.jna.tlb.excel1.AppEventsListenerHandler your texteu.doppel_helix.jna.tlb.excel1.Application ...

However, when registering an event handler in Application.advise(), it is blocked, so if you do it with threads, the error will occur as shown below.

Exception in thread "Thread-1" com.sun.jna.platform.win32.COM.COMException: advise: Interface must define a value for either iid via the ComInterface annotation at com.sun.jna.platform.win32.COM.util.ProxyObject.advise(ProxyObject.java:287) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ...

What should I do to prevent the above exception from occurring? Fundamentally, how do I catch an event where the Excel application that I ran closes? Please help me. I don't have Windows COM operation method and API knowledge.

Thank you.

I did below :

Factory factory = new Factory( myComThread ); Application excelApp= factory.createObject(Application.class); excelApp.advise(Application.class, new MyAppEventListenerHandler()); //no response. blocking

I expected when Excep application is closing I can catch that event.

1

There are 1 best solutions below

0
Eugene Astafiev On

You can handle the Application.WorkbookBeforeClose event which is fired immediately before any open workbook closes. If there is a single workbook opened the Excel Application instance can be closed with it.

Be aware, Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.

If you deal with open XML documents only you may consider using the Open XML SDK instead of automating Excel. See Welcome to the Open XML SDK 2.5 for Office for more information about that.