Java/SWT JFace Eclipse/WIN32

Материал из Java эксперт
Версия от 05:56, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Embed Word in an applet

/*
 * example snippet: Embed Word in an applet
 *
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import java.applet.Applet;
public class Snippet157 extends Applet {
  org.eclipse.swt.widgets.Display display;
  org.eclipse.swt.widgets.Shell swtParent;
  java.awt.Canvas awtParent;
  public void init() {
    Thread thread = new Thread(new Runnable() {
      public void run() {
        setLayout(new java.awt.GridLayout(1, 1));
        awtParent = new java.awt.Canvas();
        add(awtParent);
        display = new org.eclipse.swt.widgets.Display();
        swtParent = org.eclipse.swt.awt.SWT_AWT.new_Shell(display,
            awtParent);
        swtParent.setLayout(new org.eclipse.swt.layout.FillLayout());
        org.eclipse.swt.ole.win32.OleFrame frame = new org.eclipse.swt.ole.win32.OleFrame(
            swtParent, org.eclipse.swt.SWT.NONE);
        org.eclipse.swt.ole.win32.OleClientSite site;
        try {
          site = new org.eclipse.swt.ole.win32.OleClientSite(frame,
              org.eclipse.swt.SWT.NONE, "Word.Document");
        } catch (org.eclipse.swt.SWTException e) {
          String str = "Create OleClientSite Error" + e.toString();
          System.out.println(str);
          return;
        }
        setSize(500, 500);
        validate();
        site.doVerb(org.eclipse.swt.ole.win32.OLE.OLEIVERB_SHOW);
        while (swtParent != null && !swtParent.isDisposed()) {
          if (!display.readAndDispatch())
            display.sleep();
        }
      }
    });
    thread.start();
  }
  public void stop() {
    if (display != null && !display.isDisposed()) {
      display.syncExec(new Runnable() {
        public void run() {
          if (swtParent != null && !swtParent.isDisposed())
            swtParent.dispose();
          swtParent = null;
          display.dispose();
          display = null;
        }
      });
      remove(awtParent);
      awtParent = null;
    }
  }
}





Find the icon of the program that edits .bmp files

/*
 * Program example snippet: find the icon of the program that edits .bmp files
 *
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class Snippet32 {
public static void main (String [] args) {
  Display display = new Display ();
  Shell shell = new Shell (display);
  Label label = new Label (shell, SWT.NONE);
  label.setText ("Can"t find icon for .bmp");
  Image image = null;
  Program p = Program.findProgram (".bmp");
  if (p != null) {
    ImageData data = p.getImageData ();
    if (data != null) {
      image = new Image (display, data);
      label.setImage (image);
    }
  }
  label.pack ();
  shell.pack ();
  shell.open ();
  while (!shell.isDisposed()) {
    if (!display.readAndDispatch ()) display.sleep ();
  }
  if (image != null) image.dispose ();
  display.dispose ();
}
}





How to access About, Preferences and Quit menus on carbon

/*******************************************************************************
 * Copyright (c) 2000, 2005 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.swt.snippets;
/*
 * How to access About, Preferences and Quit menus on carbon.
 * NOTE: This snippet uses internal SWT packages that are
 * subject to change without notice.
 * 
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.internal.*;
import org.eclipse.swt.internal.carbon.*;
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
public class Snippet178 {
  private static final int kHICommandPreferences = ("p" << 24) + ("r" << 16)
      + ("e" << 8) + "f";
  private static final int kHICommandAbout = ("a" << 24) + ("b" << 16)
      + ("o" << 8) + "u";
  private static final int kHICommandServices = ("s" << 24) + ("e" << 16)
      + ("r" << 8) + "v";
public static void main(String[] arg) {
  Display.setAppName("AppMenu"); // sets name in Dock
  Display display = new Display();
  hookApplicationMenu(display, "About AppMenu");
  Shell shell = new Shell(display);
  shell.setText("Main Window");
  shell.open();
  while (!shell.isDisposed())
    if (!display.readAndDispatch())
      display.sleep();
  display.dispose();
}
static void hookApplicationMenu(Display display, final String aboutName) {
  // Callback target
  Object target = new Object() {
    int commandProc(int nextHandler, int theEvent, int userData) {
      if (OS.GetEventKind(theEvent) == OS.kEventProcessCommand) {
        HICommand command = new HICommand();
        OS.GetEventParameter(theEvent, OS.kEventParamDirectObject,
            OS.typeHICommand, null, HICommand.sizeof, null,
            command);
        switch (command.rumandID) {
        case kHICommandPreferences:
          return handleCommand("Preferences"); //$NON-NLS-1$
        case kHICommandAbout:
          return handleCommand(aboutName);
        default:
          break;
        }
      }
      return OS.eventNotHandledErr;
    }
    int handleCommand(String command) {
      Shell shell = new Shell();
      MessageBox preferences = new MessageBox(shell, SWT.ICON_WARNING);
      preferences.setText(command);
      preferences.open();
      shell.dispose();
      return OS.noErr;
    }
  };
  final Callback commandCallback = new Callback(target, "commandProc", 3); //$NON-NLS-1$
  int commandProc = commandCallback.getAddress();
  if (commandProc == 0) {
    commandCallback.dispose();
    return; // give up
  }
  // Install event handler for commands
  int[] mask = new int[] { OS.kEventClassCommand, OS.kEventProcessCommand };
  OS.InstallEventHandler(OS.GetApplicationEventTarget(), commandProc,
      mask.length / 2, mask, 0, null);
  // create About ... menu command
  int[] outMenu = new int[1];
  short[] outIndex = new short[1];
  if (OS.GetIndMenuItemWithCommandID(0, kHICommandPreferences, 1,
      outMenu, outIndex) == OS.noErr
      && outMenu[0] != 0) {
    int menu = outMenu[0];
    int l = aboutName.length();
    char buffer[] = new char[l];
    aboutName.getChars(0, l, buffer, 0);
    int str = OS.CFStringCreateWithCharacters(OS.kCFAllocatorDefault,
        buffer, l);
    OS.InsertMenuItemTextWithCFString(menu, str, (short) 0, 0,
        kHICommandAbout);
    OS.CFRelease(str);
    // add separator between About & Preferences
    OS.InsertMenuItemTextWithCFString(menu, 0, (short) 1,
        OS.kMenuItemAttrSeparator, 0);
    // enable pref menu
    OS.EnableMenuCommand(menu, kHICommandPreferences);
    // disable services menu
    OS.DisableMenuCommand(menu, kHICommandServices);
  }
  // schedule disposal of callback object
  display.disposeExec(new Runnable() {
    public void run() {
      commandCallback.dispose();
    }
  });
}
}





Invoke an external batch file

/*
 * Program example snippet: invoke an external batch file
 *
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Display;
public class Snippet105 {
  public static void main(String[] args) {
    Display display = new Display();
    Program.launch("c:\\cygwin\\cygwin.bat");
    display.dispose();
  }
}





Invoke the system text editor on autoexec.bat

/*
 * Program example snippet: invoke the system text editor on autoexec.bat
 *
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Display;
public class Snippet30 {
  public static void main(String[] args) {
    Display display = new Display();
    Program p = Program.findProgram(".txt");
    if (p != null)
      p.execute("c:\\autoexec.bat");
    display.dispose();
  }
}





OLE and ActiveX example: browse the typelibinfo for a program id

/*
 * OLE and ActiveX example snippet: browse the typelibinfo for a program id
 *
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.internal.ole.win32.TYPEATTR;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleControlSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.OleFunctionDescription;
import org.eclipse.swt.ole.win32.OlePropertyDescription;
import org.eclipse.swt.widgets.Shell;
public class Snippet81 {
  public static void main(String[] args) {
    if (args.length == 0) {
      System.out.println("Usage: java Main <program id>");
      return;
    }
    String progID = args[0];
    Shell shell = new Shell();
    OleFrame frame = new OleFrame(shell, SWT.NONE);
    OleControlSite site = null;
    OleAutomation auto = null;
    try {
      site = new OleControlSite(frame, SWT.NONE, progID);
      auto = new OleAutomation(site);
    } catch (SWTException ex) {
      System.out.println("Unable to open type library for " + progID);
      return;
    }
    TYPEATTR typeattr = auto.getTypeInfoAttributes();
    if (typeattr != null) {
      if (typeattr.cFuncs > 0)
        System.out.println("Functions for " + progID + " :\n");
      for (int i = 0; i < typeattr.cFuncs; i++) {
        OleFunctionDescription data = auto.getFunctionDescription(i);
        String argList = "";
        int firstOptionalArgIndex = data.args.length
            - data.optionalArgCount;
        for (int j = 0; j < data.args.length; j++) {
          argList += "[";
          if (j >= firstOptionalArgIndex)
            argList += "optional, ";
          argList += getDirection(data.args[j].flags) + "] "
              + getTypeName(data.args[j].type) + " "
              + data.args[j].name;
          if (j < data.args.length - 1)
            argList += ", ";
        }
        System.out.println(getInvokeKind(data.invokeKind) + " (id = "
            + data.id + ") : " + "\n\tSignature   : "
            + getTypeName(data.returnType) + " " + data.name + "("
            + argList + ")" + "\n\tDescription : "
            + data.documentation + "\n\tHelp File   : "
            + data.helpFile + "\n");
      }
      if (typeattr.cVars > 0)
        System.out.println("\n\nVariables for " + progID + " :\n");
      for (int i = 0; i < typeattr.cVars; i++) {
        OlePropertyDescription data = auto.getPropertyDescription(i);
        System.out.println("PROPERTY (id = " + data.id + ") :"
            + "\n\tName : " + data.name + "\n\tType : "
            + getTypeName(data.type) + "\n");
      }
    }
    auto.dispose();
    shell.dispose();
  }
  private static String getTypeName(int type) {
    switch (type) {
    case OLE.VT_BOOL:
      return "boolean";
    case OLE.VT_R4:
      return "float";
    case OLE.VT_R8:
      return "double";
    case OLE.VT_I4:
      return "int";
    case OLE.VT_DISPATCH:
      return "IDispatch";
    case OLE.VT_UNKNOWN:
      return "IUnknown";
    case OLE.VT_I2:
      return "short";
    case OLE.VT_BSTR:
      return "String";
    case OLE.VT_VARIANT:
      return "Variant";
    case OLE.VT_CY:
      return "Currency";
    case OLE.VT_DATE:
      return "Date";
    case OLE.VT_UI1:
      return "unsigned char";
    case OLE.VT_UI4:
      return "unsigned int";
    case OLE.VT_USERDEFINED:
      return "UserDefined";
    case OLE.VT_HRESULT:
      return "int";
    case OLE.VT_VOID:
      return "void";
    case OLE.VT_BYREF | OLE.VT_BOOL:
      return "boolean *";
    case OLE.VT_BYREF | OLE.VT_R4:
      return "float *";
    case OLE.VT_BYREF | OLE.VT_R8:
      return "double *";
    case OLE.VT_BYREF | OLE.VT_I4:
      return "int *";
    case OLE.VT_BYREF | OLE.VT_DISPATCH:
      return "IDispatch *";
    case OLE.VT_BYREF | OLE.VT_UNKNOWN:
      return "IUnknown *";
    case OLE.VT_BYREF | OLE.VT_I2:
      return "short *";
    case OLE.VT_BYREF | OLE.VT_BSTR:
      return "String *";
    case OLE.VT_BYREF | OLE.VT_VARIANT:
      return "Variant *";
    case OLE.VT_BYREF | OLE.VT_CY:
      return "Currency *";
    case OLE.VT_BYREF | OLE.VT_DATE:
      return "Date *";
    case OLE.VT_BYREF | OLE.VT_UI1:
      return "unsigned char *";
    case OLE.VT_BYREF | OLE.VT_UI4:
      return "unsigned int *";
    case OLE.VT_BYREF | OLE.VT_USERDEFINED:
      return "UserDefined *";
    }
    return "unknown " + type;
  }
  private static String getDirection(int direction) {
    String dirString = "";
    boolean comma = false;
    if ((direction & OLE.IDLFLAG_FIN) != 0) {
      dirString += "in";
      comma = true;
    }
    if ((direction & OLE.IDLFLAG_FOUT) != 0) {
      if (comma)
        dirString += ", ";
      dirString += "out";
      comma = true;
    }
    if ((direction & OLE.IDLFLAG_FLCID) != 0) {
      if (comma)
        dirString += ", ";
      dirString += "lcid";
      comma = true;
    }
    if ((direction & OLE.IDLFLAG_FRETVAL) != 0) {
      if (comma)
        dirString += ", ";
      dirString += "retval";
    }
    return dirString;
  }
  private static String getInvokeKind(int invKind) {
    switch (invKind) {
    case OLE.INVOKE_FUNC:
      return "METHOD";
    case OLE.INVOKE_PROPERTYGET:
      return "PROPERTY GET";
    case OLE.INVOKE_PROPERTYPUT:
      return "PROPERTY PUT";
    case OLE.INVOKE_PROPERTYPUTREF:
      return "PROPERTY PUT BY REF";
    }
    return "unknown " + invKind;
  }
}





OLE and ActiveX example: get events from IE control

/*
 * OLE and ActiveX example snippet: get events from IE control
 *
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.internal.ole.win32.ru;
import org.eclipse.swt.internal.ole.win32.ruObject;
import org.eclipse.swt.internal.ole.win32.GUID;
import org.eclipse.swt.internal.ole.win32.IDispatch;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleControlSite;
import org.eclipse.swt.ole.win32.OleEvent;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.OleListener;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class Snippet123 {
  public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    OleControlSite controlSite;
    try {
      OleFrame frame = new OleFrame(shell, SWT.NONE);
      controlSite = new OleControlSite(frame, SWT.NONE, "Shell.Explorer");
      controlSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
    } catch (SWTError e) {
      System.out.println("Unable to open activeX control");
      return;
    }
    shell.open();
    // IWebBrowser
    final OleAutomation webBrowser = new OleAutomation(controlSite);
    // When a new document is loaded, access the document object for the new
    // page.
    int DownloadComplete = 104;
    controlSite.addEventListener(DownloadComplete, new OleListener() {
      public void handleEvent(OleEvent event) {
        int[] htmlDocumentID = webBrowser
            .getIDsOfNames(new String[] { "Document" });
        if (htmlDocumentID == null)
          return;
        Variant pVarResult = webBrowser.getProperty(htmlDocumentID[0]);
        if (pVarResult == null || pVarResult.getType() == 0)
          return;
        // IHTMLDocument2
        OleAutomation htmlDocument = pVarResult.getAutomation();
        // Request to be notified of click, double click and key down
        // events
        EventDispatch myDispatch = new EventDispatch(
            EventDispatch.onclick);
        IDispatch idispatch = new IDispatch(myDispatch.getAddress());
        Variant dispatch = new Variant(idispatch);
        htmlDocument.setProperty(EventDispatch.onclick, dispatch);
        myDispatch = new EventDispatch(EventDispatch.ondblclick);
        idispatch = new IDispatch(myDispatch.getAddress());
        dispatch = new Variant(idispatch);
        htmlDocument.setProperty(EventDispatch.ondblclick, dispatch);
        myDispatch = new EventDispatch(EventDispatch.onkeydown);
        idispatch = new IDispatch(myDispatch.getAddress());
        dispatch = new Variant(idispatch);
        htmlDocument.setProperty(EventDispatch.onkeydown, dispatch);
        // Remember to release OleAutomation Object
        htmlDocument.dispose();
      }
    });
    // Navigate to a web site
    int[] ids = webBrowser
        .getIDsOfNames(new String[] { "Navigate", "URL" });
    Variant[] rgvarg = new Variant[] { new Variant("http://www.google.ru") };
    int[] rgdispidNamedArgs = new int[] { ids[1] };
    webBrowser.invoke(ids[0], rgvarg, rgdispidNamedArgs);
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    // Remember to release OleAutomation Object
    webBrowser.dispose();
    display.dispose();
  }
}
// EventDispatch implements a simple IDispatch interface which will be called
// when the event is fired.
class EventDispatch {
  private COMObject iDispatch;
  private int refCount = 0;
  private int eventID;
  final static int onhelp = 0x8001177d;
  final static int onclick = 0x80011778;
  final static int ondblclick = 0x80011779;
  final static int onkeyup = 0x80011776;
  final static int onkeydown = 0x80011775;
  final static int onkeypress = 0x80011777;
  final static int onmouseup = 0x80011773;
  final static int onmousedown = 0x80011772;
  final static int onmousemove = 0x80011774;
  final static int onmouseout = 0x80011771;
  final static int onmouseover = 0x80011770;
  final static int onreadystatechange = 0x80011789;
  final static int onafterupdate = 0x80011786;
  final static int onrowexit = 0x80011782;
  final static int onrowenter = 0x80011783;
  final static int ondragstart = 0x80011793;
  final static int onselectstart = 0x80011795;
  EventDispatch(int eventID) {
    this.eventID = eventID;
    createCOMInterfaces();
  }
  int getAddress() {
    return iDispatch.getAddress();
  }
  private void createCOMInterfaces() {
    iDispatch = new COMObject(new int[] { 2, 0, 0, 1, 3, 4, 8 }) {
      public int method0(int[] args) {
        return QueryInterface(args[0], args[1]);
      }
      public int method1(int[] args) {
        return AddRef();
      }
      public int method2(int[] args) {
        return Release();
      }
      // method3 GetTypeInfoCount - not implemented
      // method4 GetTypeInfo - not implemented
      // method5 GetIDsOfNames - not implemented
      public int method6(int[] args) {
        return Invoke(args[0], args[1], args[2], args[3], args[4],
            args[5], args[6], args[7]);
      }
    };
  }
  private void disposeCOMInterfaces() {
    if (iDispatch != null)
      iDispatch.dispose();
    iDispatch = null;
  }
  private int AddRef() {
    refCount++;
    return refCount;
  }
  private int Invoke(int dispIdMember, int riid, int lcid, int dwFlags,
      int pDispParams, int pVarResult, int pExcepInfo, int pArgErr) {
    switch (eventID) {
    case onhelp:
      System.out.println("onhelp");
      break;
    case onclick:
      System.out.println("onclick");
      break;
    case ondblclick:
      System.out.println("ondblclick");
      break;
    case onkeyup:
      System.out.println("onkeyup");
      break;
    case onkeydown:
      System.out.println("onkeydown");
      break;
    case onkeypress:
      System.out.println("onkeypress");
      break;
    case onmouseup:
      System.out.println("onmouseup");
      break;
    case onmousedown:
      System.out.println("onmousedown");
      break;
    case onmousemove:
      System.out.println("onmousemove");
      break;
    case onmouseout:
      System.out.println("onmouseout");
      break;
    case onmouseover:
      System.out.println("onmouseover");
      break;
    case onreadystatechange:
      System.out.println("onreadystatechange");
      break;
    case onafterupdate:
      System.out.println("onafterupdate");
      break;
    case onrowexit:
      System.out.println("onrowexit");
      break;
    case onrowenter:
      System.out.println("onrowenter");
      break;
    case ondragstart:
      System.out.println("ondragstart");
      break;
    case onselectstart:
      System.out.println("onselectstart");
      break;
    }
    return COM.S_OK;
  }
  private int QueryInterface(int riid, int ppvObject) {
    if (riid == 0 || ppvObject == 0)
      return COM.E_INVALIDARG;
    GUID guid = new GUID();
    COM.MoveMemory(guid, riid, GUID.sizeof);
    if (COM.IsEqualGUID(guid, COM.IIDIUnknown)
        || COM.IsEqualGUID(guid, COM.IIDIDispatch)) {
      COM.MoveMemory(ppvObject, new int[] { iDispatch.getAddress() }, 4);
      AddRef();
      return COM.S_OK;
    }
    COM.MoveMemory(ppvObject, new int[] { 0 }, 4);
    return COM.E_NOINTERFACE;
  }
  int Release() {
    refCount--;
    if (refCount == 0) {
      disposeCOMInterfaces();
    }
    return refCount;
  }
}





OLE and ActiveX example snippet

/*
 * Copyright (c) 2000, 2003 IBM Corp. All rights reserved. This file is made
 * available under the terms of the Common Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 */
/*
 * OLE and ActiveX example snippet: browse the typelibinfo for a program id
 * 
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/i.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.internal.ole.win32.TYPEATTR;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleControlSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.OleFunctionDescription;
import org.eclipse.swt.ole.win32.OlePropertyDescription;
import org.eclipse.swt.widgets.Shell;
public class Main {
  public static void main(String[] args) {
    if (args.length == 0) {
      System.out.println("Usage: java Main <program id>");
      return;
    }
    String progID = args[0];
    Shell shell = new Shell();
    OleFrame frame = new OleFrame(shell, SWT.NONE);
    OleControlSite site = null;
    OleAutomation auto = null;
    try {
      site = new OleControlSite(frame, SWT.NONE, progID);
      auto = new OleAutomation(site);
    } catch (SWTException ex) {
      System.out.println("Unable to open type library for " + progID);
      return;
    }
    TYPEATTR typeattr = auto.getTypeInfoAttributes();
    if (typeattr != null) {
      if (typeattr.cFuncs > 0)
        System.out.println("Functions for " + progID + " :\n");
      for (int i = 0; i < typeattr.cFuncs; i++) {
        OleFunctionDescription data = auto.getFunctionDescription(i);
        String argList = "";
        int firstOptionalArgIndex =
          data.args.length - data.optionalArgCount;
        for (int j = 0; j < data.args.length; j++) {
          argList += "[";
          if (j >= firstOptionalArgIndex)
            argList += "optional, ";
          argList += getDirection(data.args[j].flags)
            + "] "
            + getTypeName(data.args[j].type)
            + " "
            + data.args[j].name;
          if (j < data.args.length - 1)
            argList += ", ";
        }
        System.out.println(
          getInvokeKind(data.invokeKind)
            + " (id = "
            + data.id
            + ") : "
            + "\n\tSignature   : "
            + getTypeName(data.returnType)
            + " "
            + data.name
            + "("
            + argList
            + ")"
            + "\n\tDescription : "
            + data.documentation
            + "\n\tHelp File   : "
            + data.helpFile
            + "\n");
      }
      if (typeattr.cVars > 0)
        System.out.println("\n\nVariables for " + progID + " :\n");
      for (int i = 0; i < typeattr.cVars; i++) {
        OlePropertyDescription data = auto.getPropertyDescription(i);
        System.out.println(
          "PROPERTY (id = "
            + data.id
            + ") :"
            + "\n\tName : "
            + data.name
            + "\n\tType : "
            + getTypeName(data.type)
            + "\n");
      }
    }
    auto.dispose();
    shell.dispose();
  }
  
  private static String getTypeName(int type) {
    switch (type) {
      case OLE.VT_BOOL :
        return "boolean";
      case OLE.VT_R4 :
        return "float";
      case OLE.VT_R8 :
        return "double";
      case OLE.VT_I4 :
        return "int";
      case OLE.VT_DISPATCH :
        return "IDispatch";
      case OLE.VT_UNKNOWN :
        return "IUnknown";
      case OLE.VT_I2 :
        return "short";
      case OLE.VT_BSTR :
        return "String";
      case OLE.VT_VARIANT :
        return "Variant";
      case OLE.VT_CY :
        return "Currency";
      case OLE.VT_DATE :
        return "Date";
      case OLE.VT_UI1 :
        return "unsigned char";
      case OLE.VT_UI4 :
        return "unsigned int";
      case OLE.VT_USERDEFINED :
        return "UserDefined";
      case OLE.VT_HRESULT :
        return "int";
      case OLE.VT_VOID :
        return "void";
      case OLE.VT_BYREF | OLE.VT_BOOL :
        return "boolean *";
      case OLE.VT_BYREF | OLE.VT_R4 :
        return "float *";
      case OLE.VT_BYREF | OLE.VT_R8 :
        return "double *";
      case OLE.VT_BYREF | OLE.VT_I4 :
        return "int *";
      case OLE.VT_BYREF | OLE.VT_DISPATCH :
        return "IDispatch *";
      case OLE.VT_BYREF | OLE.VT_UNKNOWN :
        return "IUnknown *";
      case OLE.VT_BYREF | OLE.VT_I2 :
        return "short *";
      case OLE.VT_BYREF | OLE.VT_BSTR :
        return "String *";
      case OLE.VT_BYREF | OLE.VT_VARIANT :
        return "Variant *";
      case OLE.VT_BYREF | OLE.VT_CY :
        return "Currency *";
      case OLE.VT_BYREF | OLE.VT_DATE :
        return "Date *";
      case OLE.VT_BYREF | OLE.VT_UI1 :
        return "unsigned char *";
      case OLE.VT_BYREF | OLE.VT_UI4 :
        return "unsigned int *";
      case OLE.VT_BYREF | OLE.VT_USERDEFINED :
        return "UserDefined *";
    }
    return "unknown " + type;
  }
  
  private static String getDirection(int direction) {
    String dirString = "";
    boolean comma = false;
    if ((direction & OLE.IDLFLAG_FIN) != 0) {
      dirString += "in";
      comma = true;
    }
    if ((direction & OLE.IDLFLAG_FOUT) != 0) {
      if (comma)
        dirString += ", ";
      dirString += "out";
      comma = true;
    }
    if ((direction & OLE.IDLFLAG_FLCID) != 0) {
      if (comma)
        dirString += ", ";
      dirString += "lcid";
      comma = true;
    }
    if ((direction & OLE.IDLFLAG_FRETVAL) != 0) {
      if (comma)
        dirString += ", ";
      dirString += "retval";
    }
    return dirString;
  }
  
  private static String getInvokeKind(int invKind) {
    switch (invKind) {
      case OLE.INVOKE_FUNC :
        return "METHOD";
      case OLE.INVOKE_PROPERTYGET :
        return "PROPERTY GET";
      case OLE.INVOKE_PROPERTYPUT :
        return "PROPERTY PUT";
      case OLE.INVOKE_PROPERTYPUTREF :
        return "PROPERTY PUT BY REF";
    }
    return "unknown " + invKind;
  }
}





Place an icon with a popup menu on the system tray

/*
 * Tray example snippet: place an icon with a popup menu on the system tray
 *
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;
public class Snippet143 {
  public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    Image image = new Image(display, 16, 16);
    final Tray tray = display.getSystemTray();
    if (tray == null) {
      System.out.println("The system tray is not available");
    } else {
      final TrayItem item = new TrayItem(tray, SWT.NONE);
      item.setToolTipText("SWT TrayItem");
      item.addListener(SWT.Show, new Listener() {
        public void handleEvent(Event event) {
          System.out.println("show");
        }
      });
      item.addListener(SWT.Hide, new Listener() {
        public void handleEvent(Event event) {
          System.out.println("hide");
        }
      });
      item.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event event) {
          System.out.println("selection");
        }
      });
      item.addListener(SWT.DefaultSelection, new Listener() {
        public void handleEvent(Event event) {
          System.out.println("default selection");
        }
      });
      final Menu menu = new Menu(shell, SWT.POP_UP);
      for (int i = 0; i < 8; i++) {
        MenuItem mi = new MenuItem(menu, SWT.PUSH);
        mi.setText("Item" + i);
      }
      item.addListener(SWT.MenuDetect, new Listener() {
        public void handleEvent(Event event) {
          menu.setVisible(true);
        }
      });
      item.setImage(image);
    }
    shell.setBounds(50, 50, 300, 200);
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    image.dispose();
    display.dispose();
  }
}





Reading and writing to a SAFEARRAY

/*
 * Reading and writing to a SAFEARRAY
 * 
 * This example reads from a PostData object in a BeforeNavigate2 event and
 * creates a PostData object in a call to Navigate.
 * 
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.internal.win32.OS;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleControlSite;
import org.eclipse.swt.ole.win32.OleEvent;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.OleListener;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class Snippet186 {
  static int CodePage = OS.GetACP();
  public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(2, false));
    final Text text = new Text(shell, SWT.BORDER);
    text
        .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
            1, 1));
    Button go = new Button(shell, SWT.PUSH);
    go.setText("Go");
    OleFrame oleFrame = new OleFrame(shell, SWT.NONE);
    oleFrame.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2,
        1));
    OleControlSite controlSite;
    OleAutomation automation;
    try {
      controlSite = new OleControlSite(oleFrame, SWT.NONE,
          "Shell.Explorer");
      automation = new OleAutomation(controlSite);
      controlSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
    } catch (SWTException ex) {
      return;
    }
    final OleAutomation auto = automation;
    go.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event e) {
        String url = text.getText();
        int[] rgdispid = auto.getIDsOfNames(new String[] { "Navigate",
            "URL" });
        int dispIdMember = rgdispid[0];
        Variant[] rgvarg = new Variant[1];
        rgvarg[0] = new Variant(url);
        int[] rgdispidNamedArgs = new int[1];
        rgdispidNamedArgs[0] = rgdispid[1];
        auto.invoke(dispIdMember, rgvarg, rgdispidNamedArgs);
      }
    });
    // Read PostData whenever we navigate to a site that uses it
    int BeforeNavigate2 = 0xfa;
    controlSite.addEventListener(BeforeNavigate2, new OleListener() {
      public void handleEvent(OleEvent event) {
        Variant url = event.arguments[1];
        Variant postData = event.arguments[4];
        if (postData != null) {
          System.out.println("PostData = " + readSafeArray(postData)
              + ", URL = " + url.getString());
        }
      }
    });
    // Navigate to this web site which uses post data to fill in the text
    // field
    // and put the string "hello world" into the text box
    text.setText("file://"
        + Snippet186.class.getResource("Snippet186.html").getFile());
    int[] rgdispid = automation.getIDsOfNames(new String[] { "Navigate",
        "URL", "PostData" });
    int dispIdMember = rgdispid[0];
    Variant[] rgvarg = new Variant[2];
    rgvarg[0] = new Variant(text.getText());
    rgvarg[1] = writeSafeArray("hello world");
    int[] rgdispidNamedArgs = new int[2];
    rgdispidNamedArgs[0] = rgdispid[1];
    rgdispidNamedArgs[1] = rgdispid[2];
    automation.invoke(dispIdMember, rgvarg, rgdispidNamedArgs);
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    display.dispose();
  }
  // The following structs are accessed in the readSafeArray and
  // writeSafeArray
  // functions:
  //
  // VARIANT:
  // short vt
  // short wReserved1
  // short wReserved2
  // short wReserved3
  // int parray
  //
  // SAFEARRAY:
  // short cDims // Count of dimensions in this array
  // short fFeatures // Flags used by the SafeArray
  // int cbElements // Size of an element of the array
  // int cLocks // Number of times the array has been locked without
  // corresponding unlock
  // int pvData // Pointer to the data
  // SAFEARRAYBOUND[] rgsabound // One bound for each dimension
  //
  // SAFEARRAYBOUND:
  // int cElements // the number of elements in the dimension
  // int lLbound // the lower bound of the dimension
  static String readSafeArray(Variant variantByRef) {
    // Read a safearray that contains data of
    // type VT_UI1 (unsigned shorts) which contains
    // a text stream.
    int pPostData = variantByRef.getByRef();
    short[] vt_type = new short[1];
    OS.MoveMemory(vt_type, pPostData, 2);
    String result = null;
    if (vt_type[0] == (short) (OLE.VT_BYREF | OLE.VT_VARIANT)) {
      int[] pVariant = new int[1];
      OS.MoveMemory(pVariant, pPostData + 8, 4);
      vt_type = new short[1];
      OS.MoveMemory(vt_type, pVariant[0], 2);
      if (vt_type[0] == (short) (OLE.VT_ARRAY | OLE.VT_UI1)) {
        int[] pSafearray = new int[1];
        OS.MoveMemory(pSafearray, pVariant[0] + 8, 4);
        short[] cDims = new short[1];
        OS.MoveMemory(cDims, pSafearray[0], 2);
        int[] pvData = new int[1];
        OS.MoveMemory(pvData, pSafearray[0] + 12, 4);
        int safearrayboundOffset = 0;
        for (int i = 0; i < cDims[0]; i++) {
          int[] cElements = new int[1];
          OS.MoveMemory(cElements, pSafearray[0] + 16
              + safearrayboundOffset, 4);
          safearrayboundOffset += 8;
          int cchWideChar = OS.MultiByteToWideChar(CodePage,
              OS.MB_PRECOMPOSED, pvData[0], -1, null, 0);
          if (cchWideChar == 0)
            return null;
          char[] lpWideCharStr = new char[cchWideChar - 1];
          OS.MultiByteToWideChar(CodePage, OS.MB_PRECOMPOSED,
              pvData[0], -1, lpWideCharStr, lpWideCharStr.length);
          result = new String(lpWideCharStr);
        }
      }
    }
    return result;
  }
  static Variant writeSafeArray(String string) {
    // Create a one dimensional safearray containing two VT_UI1 values
    // where VT_UI1 is an unsigned char
    // Define cDims, fFeatures and cbElements
    short cDims = 1;
    short FADF_FIXEDSIZE = 0x10;
    short FADF_HAVEVARTYPE = 0x80;
    short fFeatures = (short) (FADF_FIXEDSIZE | FADF_HAVEVARTYPE);
    int cbElements = 1;
    // Create a pointer and copy the data into it
    int count = string.length();
    char[] chars = new char[count + 1];
    string.getChars(0, count, chars, 0);
    int cchMultiByte = OS.WideCharToMultiByte(CodePage, 0, chars, -1, null,
        0, null, null);
    if (cchMultiByte == 0)
      return null;
    int pvData = OS.GlobalAlloc(OS.GMEM_FIXED | OS.GMEM_ZEROINIT,
        cchMultiByte);
    OS.WideCharToMultiByte(CodePage, 0, chars, -1, pvData, cchMultiByte,
        null, null);
    int cElements1 = cchMultiByte;
    int lLbound1 = 0;
    // Create a safearray in memory
    // 12 bytes for cDims, fFeatures and cbElements + 4 bytes for pvData +
    // number of dimensions * (size of safearraybound)
    int sizeofSafeArray = 12 + 4 + 1 * 8;
    int pSafeArray = OS.GlobalAlloc(OS.GMEM_FIXED | OS.GMEM_ZEROINIT,
        sizeofSafeArray);
    // Copy the data into the safe array
    int offset = 0;
    OS.MoveMemory(pSafeArray + offset, new short[] { cDims }, 2);
    offset += 2;
    OS.MoveMemory(pSafeArray + offset, new short[] { fFeatures }, 2);
    offset += 2;
    OS.MoveMemory(pSafeArray + offset, new int[] { cbElements }, 4);
    offset += 4;
    OS.MoveMemory(pSafeArray + offset, new int[] { 0 }, 4);
    offset += 4;
    OS.MoveMemory(pSafeArray + offset, new int[] { pvData }, 4);
    offset += 4;
    OS.MoveMemory(pSafeArray + offset, new int[] { cElements1 }, 4);
    offset += 4;
    OS.MoveMemory(pSafeArray + offset, new int[] { lLbound1 }, 4);
    offset += 4;
    // Create a variant in memory to hold the safearray
    int pVariant = OS.GlobalAlloc(OS.GMEM_FIXED | OS.GMEM_ZEROINIT,
        Variant.sizeof);
    short vt = (short) (OLE.VT_ARRAY | OLE.VT_UI1);
    OS.MoveMemory(pVariant, new short[] { vt }, 2);
    OS.MoveMemory(pVariant + 8, new int[] { pSafeArray }, 4);
    // Create a by ref variant
    Variant variantByRef = new Variant(pVariant,
        (short) (OLE.VT_BYREF | OLE.VT_VARIANT));
    return variantByRef;
  }
}





Running a script within IE.

import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleControlSite;
import org.eclipse.swt.ole.win32.OleEvent;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.OleListener;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/*
 * Running a script within IE.
 * 
 * For a list of all SWT example snippets see
 * http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
 */
public class Snippet187 {
  public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    OleControlSite controlSite;
    try {
      OleFrame frame = new OleFrame(shell, SWT.NONE);
      controlSite = new OleControlSite(frame, SWT.NONE, "Shell.Explorer");
      controlSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
    } catch (SWTError e) {
      System.out.println("Unable to open activeX control");
      return;
    }
    // IWebBrowser
    final OleAutomation webBrowser = new OleAutomation(controlSite);
    // When the document is loaded, access the document object for the new
    // page
    // and evalute expression using Script.
    int DownloadComplete = 104;
    controlSite.addEventListener(DownloadComplete, new OleListener() {
      public void handleEvent(OleEvent event) {
        int[] htmlDocumentID = webBrowser
            .getIDsOfNames(new String[] { "Document" });
        if (htmlDocumentID == null)
          return;
        Variant pVarResult = webBrowser.getProperty(htmlDocumentID[0]);
        if (pVarResult == null || pVarResult.getType() == 0)
          return;
        // IHTMLDocument2
        OleAutomation htmlDocument = null;
        try {
          htmlDocument = pVarResult.getAutomation();
          pVarResult.dispose();
          int[] scriptID = htmlDocument
              .getIDsOfNames(new String[] { "Script" });
          if (scriptID == null)
            return;
          pVarResult = htmlDocument.getProperty(scriptID[0]);
          if (pVarResult == null || pVarResult.getType() == 0)
            return;
          OleAutomation htmlWindow = null;
          try {
            // IHTMLWindow2
            htmlWindow = pVarResult.getAutomation();
            pVarResult.dispose();
            int[] evaluateID = htmlWindow
                .getIDsOfNames(new String[] { "evaluate" });
            if (evaluateID == null)
              return;
            String expression = "5+Math.sin(9)";
            Variant[] rgvarg = new Variant[] { new Variant(
                expression) };
            pVarResult = htmlWindow.invoke(evaluateID[0], rgvarg,
                null);
            if (pVarResult == null || pVarResult.getType() == 0)
              return;
            System.out.println(expression + " ="
                + pVarResult.getString());
          } finally {
            htmlWindow.dispose();
          }
        } finally {
          htmlDocument.dispose();
        }
      }
    });
    // Navigate to a web site
    int[] ids = webBrowser
        .getIDsOfNames(new String[] { "Navigate", "URL" });
    Variant[] rgvarg = new Variant[] { new Variant(
        "http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet187.html") };
    int[] rgdispidNamedArgs = new int[] { ids[1] };
    webBrowser.invoke(ids[0], rgvarg, rgdispidNamedArgs);
    shell.open();
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    // Remember to release OleAutomation Object
    webBrowser.dispose();
    display.dispose();
  }
}





SWT Ole Frame

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleControlSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class SWTOleFrame {
  public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setSize(600, 400);
    shell.setLayout(new FillLayout());
    OleControlSite oleControlSite;
    OleFrame oleFrame = new OleFrame(shell, SWT.NONE);
    oleControlSite = new OleControlSite(oleFrame, SWT.NONE,
        "Shell.Explorer");
    oleControlSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
    shell.open();
    final OleAutomation browser = new OleAutomation(oleControlSite);
    int[] browserIDs = browser.getIDsOfNames(new String[] { "Navigate",
        "URL" });
    Variant[] address = new Variant[] { new Variant(
        "http://www.oreilly.ru") };
    browser.invoke(browserIDs[0], address, new int[] { browserIDs[1] });
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch())
        display.sleep();
    }
    browser.dispose();
    display.dispose();
  }
}





Word OLE

/*******************************************************************************
 * All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
 * 
 * Created on 2004-6-21 18:48:57 by JACK $Id$
 *  
 ******************************************************************************/

import java.io.File;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleClientSite;
import org.eclipse.swt.ole.win32.OleControlSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
public class WordOLE extends ApplicationWindow {
  OleFrame oleFrame;
  OleClientSite clientSite;
  OleControlSite controlSite;
  /**
   * @param parentShell
   */
  public WordOLE(Shell parentShell) {
    super(parentShell);
    addMenuBar();
    addToolBar(SWT.FLAT);
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.eclipse.jface.window.Window#createContents(org.eclipse.swt.widgets.ruposite)
   */
  protected Control createContents(Composite parent) {
    Composite composite = new Composite(parent, SWT.NULL);
    composite.setLayout(new FillLayout());
    oleFrame = new OleFrame(composite, SWT.NULL);
    if (getMenuBarManager() != null) {
      MenuItem windowMenu =
        new MenuItem(getMenuBarManager().getMenu(), SWT.CASCADE);
      windowMenu.setText("[Window]");
      MenuItem containerMenu =
        new MenuItem(getMenuBarManager().getMenu(), SWT.CASCADE);
      containerMenu.setText("[Container]");
      MenuItem fileMenu =
        new MenuItem(getMenuBarManager().getMenu(), SWT.CASCADE);
      fileMenu.setText("[File]");
      oleFrame.setWindowMenus(new MenuItem[] { windowMenu });
      oleFrame.setContainerMenus(new MenuItem[] { containerMenu });
      oleFrame.setFileMenus(new MenuItem[] { fileMenu });
      System.out.println("menu set");
    }
    clientSite =
      new OleClientSite(oleFrame, SWT.NULL, new File("test.doc"));
    // clientSite = new OleClientSite(oleFrame, SWT.NONE,
    // "Word.Document.8");
    //   clientSite = new OleControlSite(oleFrame, SWT.NONE,
    //   "Word.Document.8");
    System.out.println(clientSite.getProgramID() + ", " + clientSite);
    clientSite.doVerb(OLE.OLEIVERB_SHOW);
    return composite;
  }
  /*
   * (non-Javadoc)
   * 
   * @see org.eclipse.jface.window.ApplicationWindow#createToolBarManager(int)
   */
  protected ToolBarManager createToolBarManager(int style) {
    ToolBarManager manager = new ToolBarManager(style);
    Action actionSaveAs = new Action("Save as") {
      public void run() {
        FileDialog dialog = new FileDialog(getShell(), SWT.SAVE);
        String path = dialog.open();
        if (path != null) {
          if (clientSite.save(new File(path), false)) {
            System.out.println("Saved to file successfully.");
          } else {
            System.err.println("Failed to save to file");
          }
        }
      }
    };
    Action actionDeactivate = new Action("Deactivate") {
      public void run() {
        clientSite.deactivateInPlaceClient();
      }
    };
    Action actionSpellCheck = new Action("Spell check") {
      public void run() {
        if ((clientSite.queryStatus(OLE.OLECMDID_SPELL)
          & OLE.OLECMDF_ENABLED)
          != 0) {
          clientSite.exec(
            OLE.OLECMDID_SPELL,
            OLE.OLECMDEXECOPT_PROMPTUSER,
            null,
            null);
        }
      }
    };
    Action actionOAGetSpellingChecked = new Action("OA: Get SpellingChecked") {
      public void run() {
        
        OleAutomation automation = new OleAutomation(clientSite);
        
        // looks up the ID for property SpellingChecked.
        int[] propertyIDs = automation.getIDsOfNames(new String[]{"SpellingChecked"});
        int propertyID = propertyIDs[0];
        
        Variant result = automation.getProperty(propertyID);
        System.out.println("SpellingChecked: " + result.getBoolean());
        
        automation.dispose();
      }
    };
    Action actionOASetSpellingChecked = new Action("OA: Set SpellingChecked") {
      public void run() {
        
        OleAutomation automation = new OleAutomation(clientSite);
        
        // looks up the ID for property SpellingChecked.
        int[] propertyIDs = automation.getIDsOfNames(new String[]{"SpellingChecked"});
        int propertyID = propertyIDs[0];
        
        boolean result = automation.setProperty(propertyID, new Variant(true));
        System.out.println(result ? "Successful" : "Failed");
        
        automation.dispose();
      }
    };    
    
    Action actionOAInvokePrintPreview = new Action("OA: Invoke Select") {
      public void run() {
        OleAutomation automation = new OleAutomation(clientSite);
        
        // looks up the ID for method Select.
        int[] methodIDs = automation.getIDsOfNames(new String[]{"Select"});
        int methodID = methodIDs[0];
        
        Variant result = automation.invoke(methodID);
        System.out.println(result != null ? "Successful" : "Failed");
        System.out.println(result);
        automation.dispose();
      }
    };    
    
    manager.add(actionSaveAs);
    manager.add(actionDeactivate);
    manager.add(actionSpellCheck);
    manager.add(actionOAGetSpellingChecked);
    manager.add(actionOASetSpellingChecked);
    manager.add(actionOAInvokePrintPreview);
    return manager;
  }
  public static void main(String[] args) {
    WordOLE wordOLE = new WordOLE(null);
    wordOLE.setBlockOnOpen(true);
    wordOLE.open();
    Display.getCurrent().dispose();
  }
}