Jacob - ocx

Jacob 调用OCX 方式:jacob-1.18

为了避免出现问题,环境如下:

1、JDK1.7 32bit  .eclipse的jre版本要和jdk一致,window->preferences->java->compiler勾选jdk 1.7  build path  配置成jdk1.7版本.

2、在项目目录下新建lib目录,将jacob.jar文件拷贝到该目录下,点build path->configbuild path ->libraries。

备注:1.jacob.jar不要放到jdk的目录下,可能有冲突

2.jacob.dll经测试放在..\jdk1.6.0_22\jre\bin下被成功引用,其他目录建议不放,防止出现奇葩问题,

/**
 * jacob-1.18 ocx 测试 JDK1.7 32bit
 */
public class JacobDemo {
    
    private static ActiveXComponent activeX;
    private static Dispatch dispath;

    static {
        /*try {
            String libFile = "jacob-1.18-x86.dll";
            InputStream inputStream = JacobDemo.class.getResourceAsStream(libFile);
            File temporaryDll = File.createTempFile("jacob", ".dll");
            FileOutputStream outputStream = new FileOutputStream(temporaryDll);
            byte[] array = new byte[8192];
            for (int i = inputStream.read(array); i != -1; i = inputStream.read(array)) {
                outputStream.write(array, 0, i);
            }
            outputStream.close();
            System.setProperty(LibraryLoader.JACOB_DLL_PATH,temporaryDll.getAbsolutePath());
            LibraryLoader.loadJacobLibrary();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        System.load("F:\\jacob\\jacob-1.18\\jacob-1.18-x86.dll");
        // 创建ActiveX控件对象
        // 可以使用CLSID,也可以使用ProgID
        activeX = new ActiveXComponent("CLSID:03EA9E7D-1ED7-4ED2-8258-03457B35EA75");
        // 获得调度对象
        dispath = activeX.getObject();
        System.out.println("The Library been loaded, and an activeX component been created");
    }

    public String sendData(String param) {
        Dispatch.call(dispath, "SendData", "");
        Variant vSubj = Dispatch.call(dispath, "RetMsg");
        String result = vSubj.getString();
        System.out.println("====" + result);
        return result;
    }

    public static void main(String[] args) {
        JacobDemo demo = new JacobDemo();
        demo.sendData("");
    }
}

附:https://stackoverflow.com/questions/16147193/cant-co-create-object-cant-find-moniker-jacob

如果需要知道你的ocx控件注册后的CLSID,可以在注册表中搜索得出:
假设我的控件名称是abc.ocx,
打开注册表:运行regedit
Ctrl+F打开查找对话框,查找abc.ocx,会展开一个目录类似:{A71B53F3-562C-451E-9F92-DCF5B8852B6E}
这个目录名即是CLSID.

 

posted on 2017-12-20 11:16  TrustNature  阅读(90)  评论(0)    收藏  举报