Communicating with MS Word
When a Silverlight 4 application is running with Elevated Permissions you can access COM objects which can be quite handy. Here we have a small example showing how to open Word and set some text.

It is important to include the following namespace when wanting to use these features:
using System.Windows.Interop;
You will also need to add a reference to the Microsoft.CSharp.dll which can be found in:
Program Files/Microsoft SDKs/Silverlight/V4.0/Libraries/Client/
<UserControl x:Class="SilverlightWord.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Button Content="Open MS Word" Width="100" Height="30" Click="Button_Click" />
</Grid>
</UserControl>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interop;
namespace SilverlightWord
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
dynamic word = ComAutomationFactory.CreateObject("Word.Application");
word.Visible = true;
dynamic doc = word.Documents.Add();
string insertText = "Hello Word from Silverlight 4!";
dynamic range = doc.Range(0, 0);
range.Text = insertText;
}
}
}
Like the Excel example we are using the new dynamic keyword present in C# 4, this allows us to grab an instance of the Word application. To open Word and display it we use:
word.Visible = true;
We then create a new Word document and add some text, there is a whole host of possibilities with the new COM access capabilities of Silverlight 4.
Post your Comments
No comments found.