以下代码使用COM打开和关闭Word文档;它不会产生任何错误。
但是,如果在运行代码之前Word已最大化,则Word菜单在程序运行后不会对鼠标或键盘操作做出反应。
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();
}
有两种方法可以解决这个问题。
到目前为止,我已经能够在以下环境中复制问题:
使用Word 2003的Windows Server 2008上不存在此问题。
整个代码如下:
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;
}
}
}
答案 0 :(得分:0)
听起来你可能在Word中找到了(又一个)错误。
您是否尝试过最小化,然后在关闭活动文档后重新模拟Word应用程序对象?
也可以尝试将其设置为Visible = false,然后Visible = true。
您可能会获得屏幕闪光,但也可能会修复功能区等。