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.

Word and Silverlight

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;
using System.Runtime.InteropServices.Automation;

namespace SilverlightWord
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            dynamic word = AutomationFactory.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.

Your Comments

michael posted

Dear author:


I do as you tell above, but the program(sliverlight project) don't work ,the error message is as following :


Could you tell me what  the proble is ?


===========================================


User code untreated System.NotSupportedException


   Message = The operation is not supported in the current context.


   StackTrace:


        Located MS.Internal.Error.MarshalXresultAsException (UInt32 hr, COMExceptionBehavior comExceptionBehavior)


        Located MS.Internal.XcpImports.CheckHResult (UInt32 hr)


        Located MS.Internal.ComAutomation.ComAutomationNative.CreateObject (String progID, IntPtr & nativeObject)


        Located MS.Internal.ComAutomation.ComAutomationServices.CreateObject (String progID, ComAutomationParamWrapService paramWrapService)


        Located System.Runtime.InteropServices.Automation.AutomationFactory.CreateObject (String progID)


        Located TCMS.Client.PrintTemplateManageControl.btnPreview_Click (Object sender, RoutedEventArgs e)


        Located System.Windows.Controls.Primitives.ButtonBase.OnClick ()


        Located System.Windows.Controls.Button.OnClick ()


        Located System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp (MouseButtonEventArgs e)


        Located System.Windows.Controls.Control.OnMouseLeftButtonUp (Control ctrl, EventArgs e)


        Located MS.Internal.JoltHelper.FireEvent (IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)


   InnerException:



-----------------------------------------------------------------


michael posted

what 's the problem?,the error is as following :


============================================



用户代码未处理 System.NotSupportedException


  Message=此操作在当前上下文中不受支持。


  StackTrace:


       位于 MS.Internal.Error.MarshalXresultAsException(UInt32 hr, COMExceptionBehavior comExceptionBehavior)


       位于 MS.Internal.XcpImports.CheckHResult(UInt32 hr)


       位于 MS.Internal.ComAutomation.ComAutomationNative.CreateObject(String progID, IntPtr& nativeObject)


       位于 MS.Internal.ComAutomation.ComAutomationServices.CreateObject(String progID, ComAutomationParamWrapService paramWrapService)


       位于 System.Runtime.InteropServices.Automation.AutomationFactory.CreateObject(String progID)


       位于 TCMS.Client.PrintTemplateManageControl.btnPreview_Click(Object sender, RoutedEventArgs e)


       位于 System.Windows.Controls.Primitives.ButtonBase.OnClick()


       位于 System.Windows.Controls.Button.OnClick()


       位于 System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)


       位于 System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)


       位于 MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)


  InnerException:


xyz posted

When I tried executing the above code, I am getting a exception call "NOT SUPPORTED EXCEPTION"


Mark Kamoski posted

Dear Author -



Please help.



Do you know how to input and output Word documents to and from Silverlight?



As your excellent example shows, it is possible to launch Word from a Silverlight application.



However, what I want to do is to be able to import and export Word documents to and from a Silverlight application



I could use DOC format or ODF format or RTF format or some other document format, as long as the document format supports full editing in Silverlight, with embedded images in the document.



How can that goal be achieved?



Please advise.



Thank you.



- Mark Kamoski


Badam Santhosh posted

When I tried executing the above code, I am getting a exception call "NOT SUPPORTED EXCEPTION".


Please help me out.


Zhao posted

I cann't find the namespace of "using System.Runtime.InteropServices.Automation;"


How to get?


sajen posted

how can i add an image to word?


balu posted

is it possible to save the contents of a textbox as .doc file


regards


balu


spam-dev posted

can i use in silverlight without OOB.


devsolution


h posted

how to set the word table style?



such as "oTable.Borders.OutsideLineStyle =  Word.WdLineStyle.wdLineStyleSingle;




there is no Word.WdLineStyle.wdLineStyleSingle


DavidH posted

Do you think you would be able to do the same thing with a fillable PDF form?


dan posted

Hi Vlad & lsym1985,



Yest, you must be running in OOB and have Elevated Permissions to use COM.



Thanks!


vlad posted

Hi,



This feature is available only in OOB mode?



Thanks


Vlad


lsym1985 posted

how I can access MSWordCOM,I have no Permission


 

Post your Comments

Rate this: 

1 Star 2 Star 3 Star 4 Star 5 Star
23 Ratings / 3.9 Average
 
Latest Games
Car Parking
Jan 16, 2016
Plays: 42

Car Parking - Free iPhone, iPad, Android Physics Game ScreenshotGuide the car to its parking space in this fun Car Parking game.

1 Rating / 5 Average
Trash It
Jan 11, 2016
Plays: 66

Trash It - Free iPhone, iPad, Android Physics Game ScreenshotAim for the Trash Can and get the various items of Trash in the bin.

1 Rating / 5 Average
Sky Fly
Jan 11, 2016
Plays: 68

Sky Fly - Free iPhone, iPad, Android Shooting Game ScreenshotFly your plane in this colorful vertical scrolling shoot-em-up. Blast the bad guys and collect any bonus's they leave behind.

1 Rating / 5 Average
Professor Snappy
Jan 11, 2016
Plays: 38

Professor Snappy - Free iPhone, iPad, Android Puzzle Game ScreenshotPop as many bubbles as possible in this fun and colorful bubble popping game. The levels start off easy enough but gradually get harder!

1 Rating / 5 Average
Monster Match Saga
Jan 10, 2016
Plays: 42

Monster Match Saga - Free iPhone, iPad, Android Match 3 Game ScreenshotHere we have a bunch of monsters that need to be matched up. Look out for the bomb and spinning monsters that will cause special damage!

1 Rating / 5 Average
Fly Bird Fly
Jan 10, 2016
Plays: 49

Fly Bird Fly - Free iPhone, iPad, Android Flappy Bird Game ScreenshotGuide your friendly Bird through the maze of pipes and other obstacles collecting the Stars in this cool arcade game inspired by the legendary Flappy Bird.

1 Rating / 5 Average
Life In One
Jan 10, 2016
Plays: 56

Life In One - Free iPhone, iPad, Android Strategy Game ScreenshotYou are stranded on an Alien planet. Your goal is to build a space rocket and escape. Start by building units to create power and mine the metal patches. Build defenses to defend your base from the advancing Aliens and Zombies!

1 Rating / 5 Average
X Pool
Jan 02, 2016
Plays: 113

X Pool - Free iPhone, iPad, Android Game ScreenshotPlay Pool against the computer or battle against your friends in the online mode!

1 Rating / 5 Average
Fruit Slicer
Jan 02, 2016
Plays: 46

Fruit Slicer - Free iPhone, iPad, Android Game ScreenshotSlice the fruit that is thrown up onto the screen. Slice the fruit into multiple pieces for maximum points!

2 Ratings / 5 Average
Alien Defense
Jan 02, 2016
Plays: 61

Alien Defense - Free iPhone, iPad, Android Game ScreenshotDefend against the oncoming waves of enemy alien attack. Place your gun turrets in strategic positions to destroy the attackers!

1 Rating / 5 Average
Car Dodge Extreme
Jan 01, 2016
Plays: 62

Car Dodge Extreme - Free iPhone, iPad, Android Game ScreenshotRace the wrong way up a busy road collecting the Gold and Silver coins whilst dodging the oncoming traffic!

1 Rating / 5 Average
Tic Tac Toe XL
Jan 01, 2016
Plays: 48

Tic Tac Toe XL - Free iPhone, iPad, Android Game ScreenshotPlay the classic game of Tic Tac Toe on your large screen tablet and phones. Play against a skilled computer opponent who will try to beat you at every turn.

2 Ratings / 5 Average
Submit a Game Here!