An unhandled exception of type
'System.Runtime.InteropServices.COMException' occurred in
mscorlib.dll
Additional information: Operation unavailable
Additional information: Operation unavailable
Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.
View products that this article applies to.
using Word = Microsoft.Office.Interop.Word;
private void button1_Click(object sender, System.EventArgs e)
{
}
private void button1_Click(object sender, System.EventArgs e)
{
Word.Application oWord;
System.Diagnostics.Process.Start("C:\\Program Files\\Microsoft Office\\Office10\\Winword.exe");
oWord = (Word.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
MessageBox.Show(oWord.Name);
oWord = null;
}
private void button1_Click(object sender, System.EventArgs e)
{
int iSection = 0, iTries = 0;
Word.Application oWord;
// Start Word, giving it focus.
System.Diagnostics.Process.Start("C:\\Program Files\\Microsoft Office\\Office10\\winword.exe");
// Move focus back to this form. (This ensures the Office
// application registers itself in the ROT, allowing
// GetObject to find it.)
this.Activate();
tryAgain:
try
{
// Attempt to use GetObject to reference the running
// Office application.
iSection = 1; // Attempting GetObject.
oWord = (Word.Application) System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
iSection = 0; // Resume normal error handling.
// Automate Word.
MessageBox.Show(oWord.Name + ": able to GetObject after " +
(iTries + 1) + " tries.");
oWord.ActiveDocument.Content.Text = "Hello!";
// You are finished with Automation, so release your reference.
oWord = null;
// Exit procedure.
return;
}
catch (Exception err)
{
if (iSection == 1)
{
//GetObject may have failed because the
//Shell function is asynchronous; enough time has not elapsed
//for GetObject to find the running Office application. Wait
//1/2 seconds and retry the GetObject. If you try 20 times
//and GetObject still fails, assume some other reason
//for GetObject failing and exit the procedure.
iTries++;
if (iTries < 20)
{
System.Threading.Thread.Sleep(500); // Wait 1/2 seconds.
this.Activate();
goto tryAgain; //resume code at the GetObject line
}
else
MessageBox.Show("GetObject still failing. Process ended.");
}
else
{
//iSection = 0 so use normal error handling:
MessageBox.Show(err.Message);
}
}
}
Keywords: kbpia, kbautomation, kbprb, KB316125