Search code examples
c#uwpms-wordcom

Microsoft word automation


We have an UWP application and we would like to have the following scenario:

  1. open Microsoft word from it with a document
  2. edit document
  3. close document and get data to our application.

We have an Silverlight application that uses the code below and resolves the problem nicely. Can we do something similar in UWP? Programmatically open Word and wait for instance closing.

  private void SetupWordInstance(bool visible = true)
    {
        if (AutomationFactory.IsAvailable)
        {
            _wordApp = null;

            try
            {
                _wordApp = AutomationFactory.CreateObject("Word.Application");
                _wordVersion = _wordApp.Version;
            }
            catch
            {
                try
                {
                    _wordApp = AutomationFactory.CreateObject("Word.Application");
                    _wordVersion = _wordApp.Version;
                }
                catch (Exception)
                {
                    Utils.ShowMessage(Resource.MissingWordApplicationErrorMessage);
                }
            }

            if (_wordApp != null)
            {
                AutomationEvent beforeCloseEvent = AutomationFactory.GetEvent(_wordApp, "DocumentBeforeClose");
                beforeCloseEvent.AddEventHandler(new BeforeCloseAppDelegate(BeforeCloseApp));

                AutomationEvent quitEvent = AutomationFactory.GetEvent(_wordApp, "Quit");
                quitEvent.AddEventHandler(new QuitAppDelegate(QuitApp));

                if (visible)
                {
                    _wordApp.Visible = true;
                    _wordApp.Activate();
                    FocusWordInstance();
                }
            }
        }
        else
        {
            Utils.ShowMessage(Resource.MissingAutomationErrorMessage);
        }
    }

Solution

  • There is a possibility that it can correspond by the technology called desktop bridge which Microsoft provides. Here's an explanation. Easily, it is to extract the Windows Desktop function not available in UWP and provide it together with application.

    Docs/Windows/UWP/Develop/Porting apps to Windows 10/Desktop Bridge

    The following is a sample when using Excel.

    Desktop app bridge to UWP Samples

    UWP calling Office Interop APIs

    Windows Application Packaging Project Samples

    Excel.Interop

    Since the definition of Word API is below, it seems that it can be used as above.

    Microsoft.​Office.​Interop.​Word Namespace