Search in sources :

Example 1 with WORD

use of com.sun.jna.platform.win32.WinDef.WORD in project jna by java-native-access.

the class MSOfficeDemo method testMSWord.

public void testMSWord() throws IOException {
    File demoDocument = null;
    MSWord msWord = null;
    // http://msdn.microsoft.com/en-us/library/office/ff839952(v=office.15).aspx
    // PDF format.
    LONG wdFormatPDF = new LONG(17);
    // Rich text format (RTF).
    LONG wdFormatRTF = new LONG(6);
    // Standard HTML format.
    LONG wdFormatHTML = new LONG(8);
    // Microsoft Office Word 97 - 2003 binary file format.
    LONG wdFormatDocument = new LONG(0);
    // Word default document file format. For Word 2010, this is the DOCX format.
    LONG wdFormatDocumentDefault = new LONG(16);
    // http://msdn.microsoft.com/en-us/library/office/ff838709(v=office.15).aspx
    // Original document format.
    LONG wdOriginalDocumentFormat = new LONG(1);
    // Prompt user to select a document format.
    LONG wdPromptUser = new LONG(2);
    // Microsoft Word document format.        
    LONG wdWordDocument = new LONG(0);
    try {
        msWord = new MSWord();
        System.out.println("MSWord version: " + msWord.getVersion());
        msWord.setVisible(true);
        Helper.sleep(5);
        demoDocument = Helper.createNotExistingFile("jnatest", ".doc");
        Helper.extractClasspathFileToReal("/com/sun/jna/platform/win32/COM/util/office/resources/jnatest.doc", demoDocument);
        msWord.openDocument(demoDocument.getAbsolutePath());
        msWord.insertText("Hello from JNA! \n\n");
        // wait 10sec. before closing
        Helper.sleep(10);
        // save in different formats
        // pdf format is only supported in MSWord 2007 and above
        System.out.println("Wrinting files to: " + Helper.tempDir);
        msWord.SaveAs(new File(Helper.tempDir, "jnatestSaveAs.doc").getAbsolutePath(), wdFormatDocument);
        msWord.SaveAs(new File(Helper.tempDir, "jnatestSaveAs.pdf").getAbsolutePath(), wdFormatPDF);
        msWord.SaveAs(new File(Helper.tempDir, "jnatestSaveAs.rtf").getAbsolutePath(), wdFormatRTF);
        msWord.SaveAs(new File(Helper.tempDir, "jnatestSaveAs.html").getAbsolutePath(), wdFormatHTML);
        // close and save the document
        msWord.closeActiveDocument(false);
        msWord.newDocument();
        // msWord.openDocument(currentWorkingDir + "jnatest.doc", true);
        msWord.insertText("Hello from JNA! \n Please notice that JNA can control MS Word via the new COM interface! \nHere we are creating a new word document and we save it to the 'TEMP' directory!");
        // save with no user prompt
        msWord.SaveAs(new File(Helper.tempDir, "jnatestNewDoc1.docx").getAbsolutePath(), wdFormatDocumentDefault);
        msWord.SaveAs(new File(Helper.tempDir, "jnatestNewDoc2.docx").getAbsolutePath(), wdFormatDocumentDefault);
        msWord.SaveAs(new File(Helper.tempDir, "jnatestNewDoc3.docx").getAbsolutePath(), wdFormatDocumentDefault);
        // close and save the document
        msWord.closeActiveDocument(false);
        // open 3 documents
        msWord.openDocument(new File(Helper.tempDir, "jnatestNewDoc1.docx").getAbsolutePath());
        msWord.insertText("Hello some changes from JNA!\n");
        msWord.openDocument(new File(Helper.tempDir, "jnatestNewDoc2.docx").getAbsolutePath());
        msWord.insertText("Hello some changes from JNA!\n");
        msWord.openDocument(new File(Helper.tempDir, "jnatestNewDoc3.docx").getAbsolutePath());
        msWord.insertText("Hello some changes from JNA!\n");
        // save the document and prompt the user
        msWord.Save(false, wdPromptUser);
    } catch (COMException e) {
        if (e.getExcepInfo() != null) {
            System.out.println("bstrSource: " + e.getExcepInfo().bstrSource);
            System.out.println("bstrDescription: " + e.getExcepInfo().bstrDescription);
        }
    } finally {
        if (msWord != null) {
            msWord.quit();
        }
        if (demoDocument != null && demoDocument.exists()) {
            demoDocument.delete();
        }
    }
}
Also used : COMException(com.sun.jna.platform.win32.COM.COMException) File(java.io.File) LONG(com.sun.jna.platform.win32.WinDef.LONG)

Example 2 with WORD

use of com.sun.jna.platform.win32.WinDef.WORD in project jna by java-native-access.

the class COMBindingBaseObject method oleMethod.

protected HRESULT oleMethod(int nType, VARIANT.ByReference pvResult, IDispatch pDisp, DISPID dispId, VARIANT[] pArgs) throws COMException {
    if (pDisp == null)
        throw new COMException("pDisp (IDispatch) parameter is null!");
    // variable declaration
    int _argsLen = 0;
    VARIANT[] _args = null;
    DISPPARAMS.ByReference dp = new DISPPARAMS.ByReference();
    EXCEPINFO.ByReference pExcepInfo = new EXCEPINFO.ByReference();
    IntByReference puArgErr = new IntByReference();
    // make parameter reverse ordering as expected by COM runtime
    if ((pArgs != null) && (pArgs.length > 0)) {
        _argsLen = pArgs.length;
        _args = new VARIANT[_argsLen];
        int revCount = _argsLen;
        for (int i = 0; i < _argsLen; i++) {
            _args[i] = pArgs[--revCount];
        }
    }
    // Handle special-case for property-puts!
    if (nType == OleAuto.DISPATCH_PROPERTYPUT) {
        dp.setRgdispidNamedArgs(new DISPID[] { OaIdl.DISPID_PROPERTYPUT });
    }
    // Build DISPPARAMS
    if (_argsLen > 0) {
        dp.setArgs(_args);
        // write 'DISPPARAMS' structure to memory
        dp.write();
    }
    // Apply "fix" according to
    // https://www.delphitools.info/2013/04/30/gaining-visual-basic-ole-super-powers/
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms221486(v=vs.85).aspx
    //
    // Summary: there are methods in the word typelibrary that require both
    // PROPERTYGET _and_ METHOD to be set. With only one of these set the call
    // fails.
    //
    // The article from delphitools argues, that automation compatible libraries
    // need to be compatible with VisualBasic which does not distingish methods
    // and property getters and will set both flags always.
    //
    // The MSDN article advises this behaviour: "[...] Some languages cannot 
    // distinguish between retrieving a property and calling a method. In this 
    //case, you should set the flags DISPATCH_PROPERTYGET and DISPATCH_METHOD.
    // [...]"))
    //
    // This was found when trying to bind InchesToPoints from the _Application 
    // dispatch interface of the MS Word 15 type library
    //
    // The signature according the ITypeLib Viewer (OLE/COM Object Viewer):
    // [id(0x00000172), helpcontext(0x09700172)]
    // single InchesToPoints([in] single Inches);
    final int finalNType;
    if (nType == OleAuto.DISPATCH_METHOD || nType == OleAuto.DISPATCH_PROPERTYGET) {
        finalNType = OleAuto.DISPATCH_METHOD | OleAuto.DISPATCH_PROPERTYGET;
    } else {
        finalNType = nType;
    }
    // Make the call!
    HRESULT hr = pDisp.Invoke(dispId, new REFIID(Guid.IID_NULL), LOCALE_SYSTEM_DEFAULT, new WinDef.WORD(finalNType), dp, pvResult, pExcepInfo, puArgErr);
    COMUtils.checkRC(hr, pExcepInfo, puArgErr);
    return hr;
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) HRESULT(com.sun.jna.platform.win32.WinNT.HRESULT) EXCEPINFO(com.sun.jna.platform.win32.OaIdl.EXCEPINFO) REFIID(com.sun.jna.platform.win32.Guid.REFIID) VARIANT(com.sun.jna.platform.win32.Variant.VARIANT) PointerByReference(com.sun.jna.ptr.PointerByReference) DISPIDByReference(com.sun.jna.platform.win32.OaIdl.DISPIDByReference) IntByReference(com.sun.jna.ptr.IntByReference) WinDef(com.sun.jna.platform.win32.WinDef) DISPPARAMS(com.sun.jna.platform.win32.OleAuto.DISPPARAMS)

Example 3 with WORD

use of com.sun.jna.platform.win32.WinDef.WORD in project jna by java-native-access.

the class HybdridCOMInvocationTest method testOfficeInvocationDemonstration.

public void testOfficeInvocationDemonstration() {
    // THIS IS NOT A TEST
    //
    // This reproduces the problem by using the dispatch directly.
    PointerByReference pDispatch = new PointerByReference();
    HRESULT hr = Ole32.INSTANCE.CoCreateInstance(CLSID_WORD, null, WTypes.CLSCTX_SERVER, IID_APPLICATION, pDispatch);
    if (!COMUtils.SUCCEEDED(hr)) {
        LOG.log(Level.INFO, "HybdridCOMInvocationTest test was not run, MS Word object could not be instantiated.");
        return;
    }
    Dispatch dp = new Dispatch(pDispatch.getValue());
    // DispID of InchesToPoints
    DISPID dispId = new OaIdl.DISPID(0x00000172);
    // Interface _Application of MS Word type library
    WinDef.LCID LOCALE_SYSTEM_DEFAULT = Kernel32.INSTANCE.GetSystemDefaultLCID();
    Variant.VARIANT.ByReference result = new Variant.VARIANT.ByReference();
    OaIdl.EXCEPINFO.ByReference pExcepInfo = new OaIdl.EXCEPINFO.ByReference();
    IntByReference puArgErr = new IntByReference();
    WORD wFlagsMethod = new WinDef.WORD(OleAuto.DISPATCH_METHOD);
    WORD wFlagsGet = new WinDef.WORD(OleAuto.DISPATCH_PROPERTYGET);
    WORD wFlagsCombined = new WinDef.WORD(OleAuto.DISPATCH_METHOD | OleAuto.DISPATCH_PROPERTYGET);
    OleAuto.DISPPARAMS.ByReference pDispParams = new OleAuto.DISPPARAMS.ByReference();
    VARIANT[] params = new VARIANT[] { new VARIANT(1f) };
    pDispParams.setArgs(params);
    // Call InchesToPoints as a method
    hr = dp.Invoke(dispId, new REFIID(Guid.IID_NULL), LOCALE_SYSTEM_DEFAULT, wFlagsMethod, pDispParams, result, pExcepInfo, puArgErr);
    assertTrue(COMUtils.FAILED(hr));
    // Call InchesToPoints as a property getter
    hr = dp.Invoke(dispId, new REFIID(Guid.IID_NULL), LOCALE_SYSTEM_DEFAULT, wFlagsGet, pDispParams, result, pExcepInfo, puArgErr);
    assertTrue(COMUtils.FAILED(hr));
    // Call InchesToPoints as a hybrid
    hr = dp.Invoke(dispId, new REFIID(Guid.IID_NULL), LOCALE_SYSTEM_DEFAULT, wFlagsCombined, pDispParams, result, pExcepInfo, puArgErr);
    assertTrue(COMUtils.SUCCEEDED(hr));
    assertEquals(72.0f, result.floatValue());
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) WORD(com.sun.jna.platform.win32.WinDef.WORD) HRESULT(com.sun.jna.platform.win32.WinNT.HRESULT) DISPID(com.sun.jna.platform.win32.OaIdl.DISPID) Dispatch(com.sun.jna.platform.win32.COM.Dispatch) REFIID(com.sun.jna.platform.win32.Guid.REFIID) PointerByReference(com.sun.jna.ptr.PointerByReference) IntByReference(com.sun.jna.ptr.IntByReference) VARIANT(com.sun.jna.platform.win32.Variant.VARIANT) Variant(com.sun.jna.platform.win32.Variant) OleAuto(com.sun.jna.platform.win32.OleAuto) PointerByReference(com.sun.jna.ptr.PointerByReference) WinDef(com.sun.jna.platform.win32.WinDef) OaIdl(com.sun.jna.platform.win32.OaIdl)

Example 4 with WORD

use of com.sun.jna.platform.win32.WinDef.WORD in project jna by java-native-access.

the class CallbackProxy method invokeOnThread.

void invokeOnThread(final DISPID dispIdMember, final REFIID riid, LCID lcid, WORD wFlags, final DISPPARAMS.ByReference pDispParams) {
    VARIANT[] arguments = pDispParams.getArgs();
    final Method eventMethod = CallbackProxy.this.dsipIdMap.get(dispIdMember);
    if (eventMethod == null) {
        CallbackProxy.this.comEventCallbackListener.errorReceivingCallbackEvent("No method found with dispId = " + dispIdMember, null);
        return;
    }
    /**
             * DISPPARAMs provides two different ways to pass arguments.
             *
             * Arguments can be passed as a linear list with all arguments
             * specified to a certain position (positional) or the position of
             * an argument can be passed via the rgdispidNamedArgs array
             * (named).
             *
             * pDispParams.rgvarg (length in pDispParams.cArgs) contains all
             * arguments (named + position based)
             *
             * pDispParams.rgdispidNamedArgs (length in pDispParams.cNamedArgs)
             * contains the named parameters as DISPIDs - the DISPIDs are the
             * target index in the method signature (zero based).
             *
             * Each entry in pDispParams.rgvarg is either position based or name
             * based and the position bases arguments are passed in reverse
             * order, so getting this:
             *
             * rgvarg = ["arg1", "arg2", "arg3", "arg4", "arg5"]
             * rgdispidNamedArgs = [3, 4]
             *
             * Would lead to this paramater array in the handler:
             *
             * ["arg5", "arg4", "arg3", "arg1", "arg2"]
             *
             * See also:
             * https://msdn.microsoft.com/de-de/library/windows/desktop/ms221653%28v=vs.85%29.aspx
             */
    // Arguments are converted to the JAVA side and IDispatch Interfaces
    // are wrapped into an ProxyObject if so requested.
    //
    // Out-Parameter need to be specified as VARIANT, VARIANT args are
    // not converted, so COM memory allocation rules apply.
    DISPID[] positionMap = pDispParams.getRgdispidNamedArgs();
    final Class<?>[] paramTypes = eventMethod.getParameterTypes();
    final Object[] params = new Object[paramTypes.length];
    // Handle position based parameters first
    for (int i = 0; i < params.length && (arguments.length - positionMap.length - i) > 0; i++) {
        Class targetClass = paramTypes[i];
        Variant.VARIANT varg = arguments[arguments.length - i - 1];
        params[i] = Convert.toJavaObject(varg, targetClass, factory, true, false);
    }
    for (int i = 0; i < positionMap.length; i++) {
        int targetPosition = positionMap[i].intValue();
        if (targetPosition >= params.length) {
            // If less parameters are mapped then supplied, ignore
            continue;
        }
        Class targetClass = paramTypes[targetPosition];
        Variant.VARIANT varg = arguments[i];
        params[targetPosition] = Convert.toJavaObject(varg, targetClass, factory, true, false);
    }
    // exception occurs while doing the call into the target method
    for (int i = 0; i < params.length; i++) {
        if (params[i] == null && paramTypes[i].isPrimitive()) {
            if (paramTypes[i].equals(boolean.class)) {
                params[i] = DEFAULT_BOOLEAN;
            } else if (paramTypes[i].equals(byte.class)) {
                params[i] = DEFAULT_BYTE;
            } else if (paramTypes[i].equals(short.class)) {
                params[i] = DEFAULT_SHORT;
            } else if (paramTypes[i].equals(int.class)) {
                params[i] = DEFAULT_INT;
            } else if (paramTypes[i].equals(long.class)) {
                params[i] = DEFAULT_LONG;
            } else if (paramTypes[i].equals(float.class)) {
                params[i] = DEFAULT_FLOAT;
            } else if (paramTypes[i].equals(double.class)) {
                params[i] = DEFAULT_DOUBLE;
            } else {
                throw new IllegalArgumentException("Class type " + paramTypes[i].getName() + " not mapped to primitive default value.");
            }
        }
    }
    try {
        eventMethod.invoke(comEventCallbackListener, params);
    } catch (Exception e) {
        List<String> decodedClassNames = new ArrayList<String>(params.length);
        for (Object o : params) {
            if (o == null) {
                decodedClassNames.add("NULL");
            } else {
                decodedClassNames.add(o.getClass().getName());
            }
        }
        CallbackProxy.this.comEventCallbackListener.errorReceivingCallbackEvent("Exception invoking method " + eventMethod + " supplied: " + decodedClassNames.toString(), e);
    }
}
Also used : DISPID(com.sun.jna.platform.win32.OaIdl.DISPID) Method(java.lang.reflect.Method) WString(com.sun.jna.WString) VARIANT(com.sun.jna.platform.win32.Variant.VARIANT) COMException(com.sun.jna.platform.win32.COM.COMException) VARIANT(com.sun.jna.platform.win32.Variant.VARIANT) Variant(com.sun.jna.platform.win32.Variant) ArrayList(java.util.ArrayList) List(java.util.List)

Example 5 with WORD

use of com.sun.jna.platform.win32.WinDef.WORD in project jna by java-native-access.

the class WinDefTest method testWordExtractionFromDword.

@Test
public void testWordExtractionFromDword() {
    DWORD dword = new DWORD(0x12345678);
    assertEquals(new WORD(0x5678), dword.getLow());
    assertEquals(new WORD(0x1234), dword.getHigh());
    DWORD dword2 = new DWORD(0xFFFFFFFF);
    assertEquals(new WORD(0xFFFF), dword2.getLow());
    assertEquals(new WORD(0xFFFF), dword2.getHigh());
    DWORD dword3 = new DWORD(0x00000001);
    assertEquals(new WORD(0x0001), dword3.getLow());
    assertEquals(new WORD(0x0000), dword3.getHigh());
    DWORD dword4 = new DWORD(0x00010000);
    assertEquals(new WORD(0x0000), dword4.getLow());
    assertEquals(new WORD(0x0001), dword4.getHigh());
    DWORD dword5 = new DWORD(0x0000FFFF);
    assertEquals(new WORD(0xFFFF), dword5.getLow());
    assertEquals(new WORD(0x0000), dword5.getHigh());
    DWORD dword6 = new DWORD(0xFFFF0000);
    assertEquals(new WORD(0x0000), dword6.getLow());
    assertEquals(new WORD(0xFFFF), dword6.getHigh());
}
Also used : DWORD(com.sun.jna.platform.win32.WinDef.DWORD) WORD(com.sun.jna.platform.win32.WinDef.WORD) DWORD(com.sun.jna.platform.win32.WinDef.DWORD) Test(org.junit.Test)

Aggregations

VARIANT (com.sun.jna.platform.win32.Variant.VARIANT)5 HRESULT (com.sun.jna.platform.win32.WinNT.HRESULT)4 IntByReference (com.sun.jna.ptr.IntByReference)4 PointerByReference (com.sun.jna.ptr.PointerByReference)4 COMException (com.sun.jna.platform.win32.COM.COMException)3 REFIID (com.sun.jna.platform.win32.Guid.REFIID)3 EXCEPINFO (com.sun.jna.platform.win32.OaIdl.EXCEPINFO)3 WinDef (com.sun.jna.platform.win32.WinDef)3 WORD (com.sun.jna.platform.win32.WinDef.WORD)3 File (java.io.File)3 Factory (com.sun.jna.platform.win32.COM.util.Factory)2 ComIApplication (com.sun.jna.platform.win32.COM.util.office.word.ComIApplication)2 ComWord_Application (com.sun.jna.platform.win32.COM.util.office.word.ComWord_Application)2 DISPID (com.sun.jna.platform.win32.OaIdl.DISPID)2 DISPIDByReference (com.sun.jna.platform.win32.OaIdl.DISPIDByReference)2 DISPPARAMS (com.sun.jna.platform.win32.OleAuto.DISPPARAMS)2 Variant (com.sun.jna.platform.win32.Variant)2 DWORD (com.sun.jna.platform.win32.WinDef.DWORD)2 DWORDByReference (com.sun.jna.platform.win32.WinDef.DWORDByReference)2 WString (com.sun.jna.WString)1