The following code opens and closes a Word document using COM; it does not produce any errors.
However, if prior to running the code Word was maximized then the Word menus do not react to mouse or keyboard actions after the program is run.
public static void Main(string[] args)
{
try
{
var wordDocument = GetWordDocumentName();
var wordApplication = GetWordApplication();
// Open the document.
wordApplication.Documents.Open((object)wordDocument);
// This is what causes the problem.
// Close the document.
wordApplication.ActiveDocument.Close();
Console.WriteLine("Can you use Word menus or ribbon?");
}
catch (Exception ex)
{
WriteException(ex);
}
Console.WriteLine();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
There are two ways to work around this bug.
- Ensure word is not maximized prior to running the code.
- Select another application then go back to Word.
To date I've been able to replicate the problem in the following environments:
- Windows 7 & Word 2003
- Windows 7 & Word 2007
- Windows Vista & Word 2003
The problem does not exist on Windows Server 2008 with Word 2003.
The entire code is as follows:
namespace WordMenuSharp
{
using System;
using System.IO;
using Microsoft.VisualBasic;
public class Program
{
public static void Main(string[] args)
{
try
{
var wordDocument = GetWordDocumentName();
var wordApplication = GetWordApplication();
// Open the document.
wordApplication.Documents.Open((object)wordDocument);
// This is what causes the problem.
// Close the document.
wordApplication.ActiveDocument.Close();
Console.WriteLine("Can you use Word menus or ribbon?");
}
catch (Exception ex)
{
WriteException(ex);
}
Console.WriteLine();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private static string GetWordDocumentName()
{
var fileName = Path.Combine(
Directory.GetCurrentDirectory(),
"WordMenuTest.doc"
);
if (!File.Exists(fileName))
{
throw new FileNotFoundException(
fileName + " must be created."
);
}
return fileName;
}
private static
Microsoft.Office.Interop.Word.Application GetWordApplication()
{
Microsoft.Office.Interop.Word.Application wordApplication;
try
{
wordApplication =
(Microsoft.Office.Interop.Word.Application)Interaction
.GetObject(null, "Word.Application");
}
catch (Exception ex)
{
throw new Exception(
"Error while getting Word, have you opened it." +
Environment.NewLine +
ex.Message,
ex
);
}
if (wordApplication.Documents.Count == 0)
{
throw new Exception(
"A file must already be open in Word."
);
}
return wordApplication;
}
private static void WriteException(Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine(ex.Message);
Console.ForegroundColor = ConsoleColor.White;
}
}
}