DDE for Java Examples

Opening URL in Internet Explorer

The following example opens Java.com site in a new Internet Explorer window. A conversation is established with 'Iexplore' service, 'WWW_OpenURL' topic. Then request transaction is sent, asking IE to open the site in a new window.

DDEClient client;
Conversation url = null;
client = DDEClient.getInstance();
try {
  url = client.connect("Iexplore", "WWW_OpenURL");
} catch (DDEException e) {
  // No running instance of Internet Explorer is found.
  e.printStackTrace();
  // Stopping.
  client.close();
  return;
}
// Connected to Internet Explorer
// Opening "http://www.java.com/" in a new window
try {
  url.request("http://www.java.com/,,0");
} catch(DDEException e) {
  e.printStackTrace();
}
try {url.close();} catch (Exception ignore) {}
client.close();

Sending data to and from Excel, and executing commands

The following example establishes a DDE connection with Microsoft Excel. Then it performs REQUEST operation to read data from a cell, POKE operation to change data in a cell, and EXECUTE operation to close the document.

DDEClient client;
Conversation sheet1 = null;
client = DDEClient.getInstance();
try {
  sheet1 = client.connect("Excel", "Sheet1");
  // Connected to Excel Sheet1
  String a1 = new String(sheet1.request("R1C1"));
  System.out.println("A1 value: " + a1);
  // Changing cell A1 contents to "Hello"
  sheet1.poke("R1C1", "Hello".getBytes());
  // Sending "close()" command
  sheet1.execute("[close()]");
} catch(DDEException e) {
  e.printStackTrace();
} finally {
  try {sheet1.close();} catch (Exception e) {}
}
client.close();

Monitoring changes in Excel cells

The following example listens to changes in Microsoft Excel cells. The addDDEEventListener method is used to add event handler that will respond to cell changes.

DDEClient client;
Conversation sheet1 = null;
client = DDEClient.getInstance();
// Add event handler
client.addDDEEventListener(new DDEEventListener() {
  public void onAsyncCompleted(AsyncCompletedEvent e) {}
  public void onDisconnect(DDEEvent e) {
    System.out.println("Server has closed connection");
  }
  public void onItemChanged(ItemChangedEvent e) {
    // Item has changed, print its value
    System.out.println("Topic:"
        + e.getConversation().getTopic());
    System.out.println("ItemName:"
        + e.getItemName());
    System.out.println("ItemValue:"
        + new String(e.getItemValue()));
  }
});
try {
  sheet1 = client.connect("Excel", "Sheet1");
  // Subscribe to A1 cell changes
  sheet1.startAdvice("R1C1");
  System.out.println("Press Enter to quit");
  try {
    System.in.read();
  } catch (java.io.IOException ignore) {}
  sheet1.stopAdvice("R1C1");
} catch (DDEException e) {
  e.printStackTrace();
} finally {
  try {sheet1.close();} catch (Exception e) {}
}
client.close();