1 using Word = Microsoft.Office.Interop.Word;
int _getApplicationErrorCount=0;
bool _isMsOffice = true;
/// <summary> 2 /// 獲取最後一個當前處於活動狀態的Word進程 3 /// </summary> 4 /// <param name="isLog">是否將檢測到Office版本號寫進日志,可根據項目需要刪除該功能</param> 5 /// <returns></returns> 6 public static Word.Application GetWordApplication(bool isLog) 7 { 8 try 9 { 10 Word.Application wdApp = null; 11 bool log = isLog; 12 Thread.Sleep(100); 13 if (Process.GetProcessesByName("WINWORD").ToList().Count > 0) 14 { 15 _isMsOffice = true; 16 wdApp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application"); 17 _getApplicationErrorCount = 0; 18 if (log) 19 Trace.WriteLine("檢測到使用的MS Office " + wdApp.Version); 20 } 21 else if (Process.GetProcessesByName("wps").ToList().Count > 0) 22 { 23 _isMsOffice = false; 24 if (Type.GetTypeFromProgID("Kwps.Application") != null) 25 { 26 wdApp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Kwps.Application"); 27 _getApplicationErrorCount = 0; 28 if (log) 29 Trace.WriteLine("檢測到使用的WPS Office " + wdApp.Version + ";VBA V9"); 30 } 31 else if (Type.GetTypeFromProgID("wps.Application") != null) 32 { 33 wdApp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Wps.Application"); 34 _getApplicationErrorCount = 0; 35 if (log) 36 Trace.WriteLine("檢測到使用的WPS Office " + wdApp.Version + ";VBA V8"); 37 } 38 else 39 { 40 MessageBox.Show("當前WPS 不支持VBA"); 41 } 42 } 43 else 44 { 45 wdApp = null; 46 } 47 return wdApp; 48 } 49 catch (Exception ex) 50 { 52 _getApplicationErrorCount++; 53 if (_getApplicationErrorCount <= 5) //檢測失敗重試5次 54 { 55 Thread.Sleep(200); 56 return GetWordApplication(false); 57 } 58 else 59 { 60 Trace.WriteLine("Get word application failed!" + ex.Message + ex.StackTrace); 61 _getApplicationErrorCount = 0; 62 return null; 63 } 64 } 65 }
注:
調用是可使用Word.Application wdApp = GetWordApplication(true);
獲取該進程中的所有文檔可用:Word.Documents docs = wdApp.Documents;
轉載請注明出處,謝謝!