Obtain the opened Word document and obtain the opened Word document.
1 using Word = Microsoft.Office.Interop.Word;
int _getApplicationErrorCount=0;
bool _isMsOffice = true;
/// <Summary> 2 /// obtain the last active Word process 3 /// </summary> 4 /// <param name = "isLog"> whether to write the detected Office version into the log, you can delete this function as needed </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 (1, 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 ("detected 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 detected" + 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 detected" + wdApp. version + "; VBA V8"); 37} 38 else39 {40 MessageBox. show ("Current WPS does not support VBA"); 41} 42} 43 else44 {45 wdApp = null; 46} 47 return wdApp; 48} 49 catch (Exception ex) 50 {52 _ getApplicationErrorCount ++; 53 if (_ GetApplicationErrorCount <= 5) // retry five failed detection times 54 {55 Thread. sleep (200); 56 return GetWordApplication (false); 57} 58 else59 {60 Trace. writeLine ("Get word application failed! "+ Ex. Message + ex. StackTrace); 61 _ getApplicationErrorCount = 0; 62 return null; 63} 64} 65}
Note:
You can use Word. Application wdApp = GetWordApplication (true) for the call );
Obtain all Documents in the process. Available: Word. Documents docs = wdApp. Documents ENTs;
Please indicate the source for reprinting. Thank you!