0

I am trying to automate word app. With Marshal.GetActiveObject("Word.Application") I can get object of word from ROT Table. But problem is when i call the wordApp.Name application throws "COM object that has been separated from its underlying RCW cannot be used."

protected override void OnInit()
{
    // Word Application STA Thread
    _wordApp = (Application)Marshal.GetActiveObject("Word.Application");
    Debug.WriteLine("Output : " + _wordApp?.Application.Name + " , Thread Id : " + Thread.CurrentThread.ManagedThreadId);
}
// Call From Another Thread On Event
private void HandleKeyEventOnFocus(KeyEventArgs e)
{
    try
    {
        Debug.WriteLine("Thread ID : " + Thread.CurrentThread.ManagedThreadId); // STA Thread
        if (_userInputManager.IsHotKeyPressed(Properties.Settings.Default.MS_WORD_READ_SENTENCE, e))
        {
            Thread.Sleep(300);
            // Problem
            Debug.WriteLine(_wordApp?.Name); // COM object that has been separated from its underlying RCW cannot be used.
        }
    }
    catch (Exception exception)
    {
        Debug.WriteLine(exception);
    }
}

I have failed multiple times. Is there anyone who has worked on this?

macropod
  • 12,757
  • 2
  • 9
  • 21
  • Don't know if there is a Word-specific problem but it appear this type of error has been discussed on StackOverflow, e.g. https://stackoverflow.com/questions/1567017/com-object-that-has-been-separated-from-its-underlying-rcw-cannot-be-used and articles referenced from there. Probably worth a look if you haven't done that already. – jonsson Dec 06 '22 at 13:46

0 Answers0