获取打开的Word文档

时间:2022-12-17 15:41:50
      using Word = Microsoft.Office.Interop.Word;
       int _getApplicationErrorCount=0;
       bool _isMsOffice = true;
       /// <summary>
/// 获取最后一个当前处于活动状态的Word进程
/// </summary>
/// <param name="isLog">是否将检测到Office版本号写进日志,可根据项目需要删除该功能</param>
/// <returns></returns>
public static Word.Application GetWordApplication(bool isLog)
{
try
{
Word.Application wdApp = null;
bool log = isLog;
Thread.Sleep();
if (Process.GetProcessesByName("WINWORD").ToList().Count > )
{
_isMsOffice = true;
wdApp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
_getApplicationErrorCount = ;
if (log)
Trace.WriteLine("检测到使用的MS Office " + wdApp.Version);
}
else if (Process.GetProcessesByName("wps").ToList().Count > )
{
_isMsOffice = false;
if (Type.GetTypeFromProgID("Kwps.Application") != null)
{
wdApp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Kwps.Application");
_getApplicationErrorCount = ;
if (log)
Trace.WriteLine("检测到使用的WPS Office " + wdApp.Version + ";VBA V9");
}
else if (Type.GetTypeFromProgID("wps.Application") != null)
{
wdApp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Wps.Application");
_getApplicationErrorCount = ;
if (log)
Trace.WriteLine("检测到使用的WPS Office " + wdApp.Version + ";VBA V8");
}
else
{
MessageBox.Show("当前WPS 不支持VBA");
}
}
else
{
wdApp = null;
}
return wdApp;
}
catch (Exception ex)
{
_getApplicationErrorCount++;
if (_getApplicationErrorCount <= ) //检测失败重试5次
{
Thread.Sleep();
return GetWordApplication(false);
}
else
{
Trace.WriteLine("Get word application failed!" + ex.Message + ex.StackTrace);
_getApplicationErrorCount = ;
return null;
}
}
}

注:

  调用是可使用Word.Application wdApp = GetWordApplication(true);

  获取该进程中的所有文档可用:Word.Documents docs = wdApp.Documents;

  转载请注明出处,谢谢!