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?