Last active
September 28, 2019 17:43
-
-
Save atifaziz/9252590 to your computer and use it in GitHub Desktop.
Simple NDde demo for reading and writing data to Excel using DDE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using NDde.Client; | |
// Adapted from: http://ndde.codeplex.com/discussions/399046 | |
static class Program | |
{ | |
static void Main(IEnumerable<string> args, TextReader stdin, TextWriter stdout, TextWriter stderr) | |
{ | |
var argq = new Queue<string>(args.Where(arg => !string.IsNullOrEmpty(arg))); | |
var topic = argq.Count > 0 ? argq.Dequeue() : "Book1"; | |
var inputItem = argq.Count > 0 ? argq.Dequeue() : "R1C1"; | |
var outputItem = argq.Count > 0 ? argq.Dequeue() : "R1C2"; | |
using (var client = new DdeClient("EXCEL", topic)) | |
{ | |
client.Connect(); | |
stderr.WriteLine("Connected."); | |
client.StartAdvise(inputItem, 1, true, TimeSpan.FromMinutes(1)); | |
client.Disconnected += (_, e) => { if (e.IsServerInitiated) { stderr.WriteLine("Server disconnected."); } }; | |
client.Advise += (_, e) => stdout.WriteLine(e.Text.TrimEnd('\r', '\n', '\0')); | |
string line; | |
while ((line = stdin.ReadLine()) != null) | |
{ | |
if (client.IsConnected) | |
client.Poke(outputItem, line + "\0", TimeSpan.FromSeconds(4)); | |
else | |
stderr.WriteLine("WARNING! Client no longer appears connected."); | |
} | |
} | |
} | |
static int Main(string[] args) | |
{ | |
try | |
{ | |
Main(args, Console.In, Console.Out, Console.Error); | |
return 0; | |
} | |
catch (Exception e) | |
{ | |
Console.Error.WriteLine(e.GetBaseException().Message); | |
return 1; | |
} | |
} | |
} | |
static class DdeClientExtensions | |
{ | |
public static void StartAdvise(this DdeClient client, string item, int format, bool hot, TimeSpan timeout) | |
{ | |
if (client == null) throw new ArgumentNullException("client"); | |
client.StartAdvise(item, format, hot, (int) timeout.TotalMilliseconds); | |
} | |
public static void Poke(this DdeClient client, string item, string data, TimeSpan timeout) | |
{ | |
if (client == null) throw new ArgumentNullException("client"); | |
client.Poke(item, data, (int) timeout.TotalMilliseconds); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, thank you for your great example. Our team is migrating VB app to window form application and using DDE to communicate between processes. Do you know how to using NDDE to make a communication between 2 window form app with specified control?