Exemple #1
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create Word Instance
            WordApp = OpenWordApplication();
            //Show Word
            WordApp.Visible = true;
            //Open a Word Doc
            OpenWordDocument(WordApp, "c:\\test.docx");
            DialogResult result = MessageBox.Show("Would you like to Print?", "PrintPreview", MessageBoxButtons.OKCancel);

            switch (result)
            {
            case DialogResult.OK:
            {
                WordApp.PrintPreview = true;
                //if preview call above doesn't work try the call below
                //WordApp.ActiveWindow.View.Type = Word.WdViewType.wdPrintPreview;
                break;
            }

            case DialogResult.Cancel:
            {
                CloseWordApplication(WordApp);
                break;
            }
            }
        }
Exemple #2
0
        // -----------------------------------------------------------------------
        // This method replicates an entire folder structure including files
        // It also replaces the metadata by database fields
        // -----------------------------------------------------------------------
        private void ReplicateFolderFilesReplace()
        {
            Word.ApplicationClass vkWordApp =
                new Word.ApplicationClass();

            string sourceFolder =
                "C:\\projects\\Research\\TestTemplate\\TemplateFrom";

            string destinationFolder =
                "C:\\projects\\Research\\TestTemplate\\TemplateTo";

            var ts = new List <WordDocumentTasks.TagStructure>();

            ts.Add(new WordDocumentTasks.TagStructure()
            {
                Tag = "<<XX>>", TagValue = "VV1"
            });
            ts.Add(new WordDocumentTasks.TagStructure()
            {
                Tag = "<<YY>>", TagValue = "VV2"
            });
            ts.Add(new WordDocumentTasks.TagStructure()
            {
                Tag = "<<VV>>", TagValue = "VV3"
            });

            WordDocumentTasks.CopyFolder(sourceFolder, destinationFolder);
            WordDocumentTasks.ReplaceStringInAllFiles(destinationFolder, ts, vkWordApp);
        }
		public void VerifyWmWsAddInDoesNotExist()
		{
			Word.ApplicationClass word = new Word.ApplicationClass();
			Office.COMAddIns addinsCollection = null;
			try
			{				
				addinsCollection = word.COMAddIns;
			}
			catch(System.Runtime.InteropServices.COMException)
			{
				CloseWordCleanly(word);
				return;  // Word just throws an 'unknown' error if there are no addins at all
			}
			try
			{
				bool bFoundWord = false;
				foreach( Office.COMAddIn addin in addinsCollection )
				{
					string progid = addin.ProgId;
					if(progid == "__WmWSAddin.WSWordAddIn")
						bFoundWord = true;
				}
	
				Assert.IsTrue( !bFoundWord );
				Assert.IsTrue(!File.Exists("c:\\Program Files\\Workshare\\Modules\\WmWSAddin.dll"));
			}
// No catch - we should be able to access any AddIn in the collection
			finally
			{
				CloseWordCleanly(word);
			}
		}
Exemple #4
0
 /// <summary>
 /// Preactivation
 /// It's usefull, if you need more speed in the main Program
 /// so you can preload Word.
 /// </summary>
 public void PreActivate()
 {
     if (WordApplication == null)
     {
         WordApplication = new Word.ApplicationClass();
     }
 }
 /// <summary>
 /// Preactivation
 /// It's usefull, if you need more speed in the main Program
 /// so you can preload Word.
 /// </summary>
 public void PreActivate()
 {
     if (wd == null)
     {
         wd = new Word.ApplicationClass();
     }
 }
Exemple #6
0
        public void MergeDoc(string outPutFilePath, params string[] filePath)
        {
            object oMissing = System.Reflection.Missing.Value;
            object oObject  = System.Reflection.Missing.Value;

            Word.ApplicationClass oWord = new Word.ApplicationClass();
            Word._Document        oDoc  = null;
            oWord.Visible = false;
            Word.Documents oDocs = oWord.Documents;
            try
            {
                oDoc = oDocs.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                foreach (string fs in filePath)
                {
                    if (File.Exists(fs))
                    {
                        oWord.Selection.InsertFile(fs, ref oObject, ref oObject, ref oObject, ref oObject);
                        object obj = Word.WdBreakType.wdPageBreak;
                        //oWord.Selection.InsertBreak(ref obj);
                    }
                }
                object objFinalFile = (object)outPutFilePath;
                oDoc.SaveAs(ref objFinalFile, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            }
            catch (Exception e)
            {
            }
            finally
            {
                oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Create Word Instance
            WordApp = OpenWordApplication();
            //Show Word
            WordApp.Visible = true;
            //Open a Word Doc
            OpenWordDocument(WordApp, "c:\\test.docx");
            DialogResult result = MessageBox.Show("Would you like to Print?", "PrintPreview", MessageBoxButtons.OKCancel);

            switch (result)
            {
            case DialogResult.OK:
            {
                WordApp.PrintPreview = true;
                break;
            }

            case DialogResult.Cancel:
            {
                CloseWordApplication(WordApp);
                break;
            }
            }
        }
Exemple #8
0
 public void PreActivate()
 {
     if (applicationClass == null)
     {
         applicationClass = new Word.ApplicationClass();
     }
 }
Exemple #9
0
		private void GetRevisionAndCommmentCounts(string filename, ref int revisionCount, ref int commentCount)
		{
			Word._Application wordApp = new Word.ApplicationClass();
			wordApp.Visible = false;
			object missing = System.Type.Missing;
			object falseRef = false;
			Word.Documents documents = null;
			Word.Document doc = null;
			Word.Revisions revisions = null;
			Word.Comments comments = null;
			try
			{
				documents = wordApp.Documents;
				object objFilename = filename;
				doc = documents.Open(ref objFilename, ref missing, ref missing,
					ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
					ref missing, ref missing, ref missing);

				revisions = doc.Revisions;
				revisionCount = revisions.Count;

				comments = doc.Comments;
				commentCount = comments.Count;

#pragma warning disable 467
				doc.Close(ref falseRef, ref missing, ref missing);
#pragma warning restore 467
				wordApp.Quit(ref falseRef, ref missing, ref missing);

				WaitForWordToShutDown(30000);
			}
			finally
			{
				if (null != revisions)
					System.Runtime.InteropServices.Marshal.ReleaseComObject(revisions);

				revisions = null;

				if (null != comments)
					System.Runtime.InteropServices.Marshal.ReleaseComObject(comments);

				comments = null;

				if (null != doc)
					System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);

				doc = null;

				if (null != documents)
					System.Runtime.InteropServices.Marshal.ReleaseComObject(documents);

				documents = null;

				if (null != wordApp)
					System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);

				wordApp = null;
			}
		}
Exemple #10
0
        // -----------------------------------------------------
        //   This method replicates folders and files for a given
        //   folder structure (source and destination)
        // -----------------------------------------------------
        private void ReplicateFolderFilesReplace()
        {
            Cursor.Current = Cursors.WaitCursor;

            Word.ApplicationClass vkWordApp =
                new Word.ApplicationClass();

            // The source comes from the document set
            // The destination is selected and stored also
            //

            string sourceFolder      = txtSourceFolder.Text;
            string destinationFolder = txtDestinationFolder.Text;

            if (sourceFolder == "" || destinationFolder == "")
            {
                return;
            }

            var ts = new List <WordDocumentTasks.TagStructure>();

            ts.Add(new WordDocumentTasks.TagStructure()
            {
                Tag = "<<XX>>", TagValue = "VV1"
            });
            ts.Add(new WordDocumentTasks.TagStructure()
            {
                Tag = "<<YY>>", TagValue = "VV2"
            });
            ts.Add(new WordDocumentTasks.TagStructure()
            {
                Tag = "<<VV>>", TagValue = "VV3"
            });
            ts.Add(new WordDocumentTasks.TagStructure()
            {
                Tag = "<<ClientNAME>>", TagValue = "Client 2"
            });
            ts.Add(new WordDocumentTasks.TagStructure()
            {
                Tag = "<<ClientADDRESS>>", TagValue = "St Street"
            });
            ts.Add(new WordDocumentTasks.TagStructure()
            {
                Tag = "<<ClientEMAILADDRESS>>", TagValue = "Email@com"
            });
            ts.Add(new WordDocumentTasks.TagStructure()
            {
                Tag = "<<ClientPHONE>>", TagValue = "09393893"
            });

            WordDocumentTasks.CopyFolder(sourceFolder, destinationFolder);
            WordDocumentTasks.ReplaceStringInAllFiles(destinationFolder, ts, vkWordApp);

            Cursor.Current = Cursors.Arrow;
            MessageBox.Show("Project Successfully Created.");
        }
 /// <summary>
 /// This method returns a Word.ApplicationClass Object.
 /// Tested with the Microsoft 9.0 Object Library ( COM )
 /// </summary>
 /// <returns>Word.ApplicationClass Object</returns>
 public static Word.ApplicationClass OpenWordApplication()
 {
     try
     {
         Word.ApplicationClass WordApp = new Word.ApplicationClass();
         return(WordApp);
     }
     catch (Exception e)
     {
         //show the user the error message
         MessageBox.Show(e.Message);
         return(null);
     }
 }
Exemple #12
0
        private void CreateWordFile(string strFilePath)
        {
            //Creating the instance of Word Application
            Word.Application newApp = new Word.ApplicationClass();
            object           Source = strFilePath;
            // specifying the Source & Target file names
            string strNewPath = strFilePath.Replace(".html", ".rtf");

            object Target = strNewPath;

            // Use for the parameter whose type are not known or
            // say Missing
            object Unknown = Type.Missing;

            Word.Document objDoc;
            // Source document open here
            // Additional Parameters are not known so that are
            // set as a missing type
            objDoc = newApp.Documents.Open(ref Source, ref Unknown,
                                           ref Unknown, ref Unknown, ref Unknown,
                                           ref Unknown, ref Unknown, ref Unknown,
                                           ref Unknown, ref Unknown, ref Unknown,
                                           ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);

            // Specifying the format in which you want the output file
            //object format = Word.WdSaveFormat.wdFormatDocument;
            object format = Word.WdSaveFormat.wdFormatRTF;

            objDoc.Activate();


            foreach (Word.Paragraph rPrg in newApp.ActiveDocument.Paragraphs)
            {
                rPrg.Range.Font.Name = "VNI-Times";
                rPrg.Range.Font.Size = 14;
            }
            //newApp.Selection.TypeParagraph();
            //newApp.Selection.Font.Name = "VNI-Times";
            //Changing the format of the document
            newApp.ActiveDocument.SaveAs(ref Target, ref format,
                                         ref Unknown, ref Unknown, ref Unknown,
                                         ref Unknown, ref Unknown, ref Unknown,
                                         ref Unknown, ref Unknown, ref Unknown,
                                         ref Unknown, ref Unknown, ref Unknown,
                                         ref Unknown, ref Unknown);

            newApp.ActiveDocument.Save();
            // for closing the application
            newApp.Quit(ref Unknown, ref Unknown, ref Unknown);
        }
    /// <summary>
    /// Extracts the review results from a Word document
    /// </summary>
    /// <param name="fileName">Fully qualified path of the file to be evaluated</param>
    /// <returns></returns>
    public ReviewResult GetReviewResults(string fileName)
    {
        Word.Application  wordApp     = null;
        List <ReviewItem> reviewItems = new List <ReviewItem>();
        object            missing     = System.Reflection.Missing.Value;

        try
        {
            // Fire up Word
            wordApp = new Word.ApplicationClass();
            // Some object variables because the Word API requires this
            object fileNameForWord = fileName;
            object readOnly        = true;
            WorkingDoc = wordApp.Documents.Open(ref fileNameForWord,
                                                ref missing, ref readOnly,
                                                ref missing, ref missing, ref missing, ref missing, ref missing,
                                                ref missing, ref missing, ref missing, ref missing, ref missing,
                                                ref missing, ref missing, ref missing);
            // Gather all paragraphs that are chapter headers, sorted by their start position
            var headers = (from Word.Paragraph p in WorkingDoc.Paragraphs
                           where IsHeading(p)
                           select new Heading()
            {
                Text = GetHeading(p),
                Start = p.Range.Start
            }).ToList().OrderBy(h => h.Start);
            reviewItems.AddRange(FindComments(headers));
            // I will be doing similar things with Revisions in the document
        }
        catch (Exception x)
        {
            MessageBox.Show(x.ToString(),
                            "Error while collecting review items",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
        }
        finally
        {
            if (wordApp != null)
            {
                object doNotSave = Word.WdSaveOptions.wdDoNotSaveChanges;
                wordApp.Quit(ref doNotSave, ref missing, ref missing);
            }
        }
        ReviewResult result = new ReviewResult();

        result.Items = reviewItems.OrderBy(i => i.Position);
        return(result);
    }
Exemple #14
0
        public void Quit( )
        {
            object missing = System.Reflection.Missing.Value;

            if (oDoc != null)
            {
                oDoc.Close(ref missing, ref missing, ref missing);
                oDoc = null;
            }
            if (oWordApplic != null)
            {
                oWordApplic.Application.Quit(ref missing, ref missing, ref missing);
                oWordApplic = null;
            }
        }
Exemple #15
0
        private void Initialize()
        {
            try
            {
                Title1 = Culture.Culture.Instance.GetStr("IDS_TITLE1");
                Title2 = Culture.Culture.Instance.GetStr("IDS_TITLE2");
                Title3 = Culture.Culture.Instance.GetStr("IDS_TITLE3");

                p_Word = new Word.ApplicationClass();
            }
            catch (Exception ex)
            {
                Trace.Write("Class BaseConversions -> Function Initialize failed. Cause : " + ex.Message);
                throw new Exception(ex.Message);
            }
        }
Exemple #16
0
        public string CopyToWord()
        {
            object filename = @"C:\" + System.DateTime.Now.ToFileTime() + ".doc";

            Word._Application application = new Word.ApplicationClass();
            Word._Document    document    = application.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            foreach (Excel.Worksheet sheet in wbb.Sheets)
            {
                if (sheet.Index == wbb.Sheets.Count)
                {
                    continue;
                }
                for (int i = 1; i < sheet.UsedRange.Rows.Count; i++)
                {
                    Word.Paragraph para = document.Paragraphs.Add(ref missing);
                    string         text = "";
                    for (int j = 1; j < sheet.UsedRange.Columns.Count; j++)
                    {
                        Excel.Range range = (Excel.Range)sheet.Cells[i, j];
                        if (range.Value2 != null)
                        {
                            text += range.Value2.ToString() + "\t";
                            if (range.Value2.ToString().StartsWith("#picture"))
                            {
                                string[]    value = System.Text.RegularExpressions.Regex.Split(range.Value2.ToString(), "_");
                                Excel.Shape shape = sheet.Shapes.Item(int.Parse(value[1])) as Excel.Shape;
                                shape.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlBitmap);
                                Word.Paragraph picture = document.Paragraphs.Add(ref missing);
                                picture.Range.Paste();
                                picture.Format.CharacterUnitFirstLineIndent = 2;
                                picture.Range.InsertParagraphAfter();
                                text = "";
                                i   += int.Parse(value[2]) - 1;
                                break;
                            }
                        }
                    }
                    para.Range.Text = text;
                    para.Format.CharacterUnitFirstLineIndent = 2;
                    para.Range.InsertParagraphAfter();
                }
            }
            document.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            document.Close(ref missing, ref missing, ref missing);
            application.Quit(ref missing, ref missing, ref missing);
            return(filename.ToString());
        }
Exemple #17
0
 public string CopyToWord()
 {
     object filename = @"C:\" + System.DateTime.Now.ToFileTime() + ".doc";
     Word._Application application = new Word.ApplicationClass();
     Word._Document document = application.Documents.Add(ref missing, ref missing, ref missing, ref missing);
     foreach (Excel.Worksheet sheet in wbb.Sheets)
     {
         if (sheet.Index == wbb.Sheets.Count)
         {
             continue;
         }
         for (int i = 1; i < sheet.UsedRange.Rows.Count; i++)
         {
             Word.Paragraph para = document.Paragraphs.Add(ref missing);
             string text = "";
             for (int j = 1; j < sheet.UsedRange.Columns.Count; j++)
             {
                 Excel.Range range = (Excel.Range)sheet.Cells[i, j];
                 if (range.Value2 != null)
                 {
                     text += range.Value2.ToString() + "\t";
                     if (range.Value2.ToString().StartsWith("#picture"))
                     {
                         string[] value = System.Text.RegularExpressions.Regex.Split(range.Value2.ToString(), "_");
                         Excel.Shape shape = sheet.Shapes.Item(int.Parse(value[1])) as Excel.Shape;
                         shape.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlBitmap);
                         Word.Paragraph picture = document.Paragraphs.Add(ref missing);
                         picture.Range.Paste();
                         picture.Format.CharacterUnitFirstLineIndent = 2;
                         picture.Range.InsertParagraphAfter();
                         text = "";
                         i += int.Parse(value[2]) - 1;
                         break;
                     }
                 }
             }
             para.Range.Text = text;
             para.Format.CharacterUnitFirstLineIndent = 2;
             para.Range.InsertParagraphAfter();
         }
     }
     document.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
     document.Close(ref missing, ref missing, ref missing);
     application.Quit(ref missing, ref missing, ref missing);
     return filename.ToString();
 }
 /// <summary>
 /// This method closes the Word.ApplicationClass instance that is sent
 /// as a parameter. Releasing the COM Object by Marshal seems
 /// to properly dispose of the Object.
 /// Tested with the Microsoft 9.0 Object Library ( COM )
 /// </summary>
 /// <param name="WordApp"></param>
 public static void CloseWordApplication(Word.ApplicationClass WordApp)
 {
     try
     {
         object j_SaveChanges = false;
         object j_NullObject  = System.Reflection.Missing.Value;
         WordApp.Quit(ref j_SaveChanges, ref j_NullObject, ref j_NullObject);
         Marshal.ReleaseComObject(WordApp);
         WordApp = null;
         System.GC.Collect();
         GC.WaitForPendingFinalizers();
     }
     catch (Exception e)
     {
         //show the user the error message
         MessageBox.Show(e.Message);
     }
 }
Exemple #19
0
        public void InsertFile(string path)
        {
            Word.ApplicationClass applicationClass = new Word.ApplicationClass();
            object fileName = showPath;

            Word.Document doct = applicationClass.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            doct.Activate();
            object confirmConversion = false;
            object link       = false;
            object attachment = false;

            applicationClass.Selection.InsertFile(path, ref missing, ref confirmConversion, ref link, ref attachment);
            object pBreak = (int)Word.WdBreakType.wdPageBreak;

            applicationClass.Selection.InsertBreak(ref pBreak);
            doct.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            ((Word._Document)doct).Close(ref missing, ref missing, ref missing);
        }
Exemple #20
0
 public void CloseWordApplication()
 {
     try
     {
         object saveChanges    = false;
         object originalFormat = null;
         object routeDocument  = null;
         if (this.m_WordApp != null)
         {
             this.m_WordApp.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
         }
         this.m_WordApp  = null;
         this.m_hWordWnd = IntPtr.Zero;
     }
     catch (Exception ex)
     {
         LogManager.Instance.WriteLog("WinWordControl.CloseWordApplication", ex);
     }
 }
Exemple #21
0
        public bool Replace(string strOldText, string strNewText, string path)
        {
            object missing = System.Reflection.Missing.Value;

            Word._Application wapp = new Word.ApplicationClass();
            wapp.Visible = false;
            object OBJpath = path;
            object text1   = strOldText;
            object text2   = strNewText;
            object Replace = Word.WdReplace.wdReplaceAll;

            wapp.Documents.Open(ref OBJpath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            wapp.Selection.Find.Execute(ref text1, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref text2, ref Replace, ref missing, ref missing, ref missing, ref missing);
            object SaveChangs     = true;
            object OriginalFormat = System.Type.Missing;
            object RouteDocument  = System.Type.Missing;

            wapp.Quit(ref SaveChangs, ref OriginalFormat, ref RouteDocument);
            return(true);
        }
 /// <summary>
 /// This method returns a Word.Document Object from the File Location and loads it into the
 /// Word.ApplicationClass Object. Basically it means it opens a previously saved word document.
 /// Tested with the Microsoft 9.0 Object Library ( COM )
 /// </summary>
 /// <param name="WordApp">This is the Word.ApplicationClass Object. It is the Object that contains
 /// the Word Application</param>
 /// <param name="FileLocation">This is the File Location for the Word Document you would like to open.
 /// Note that this is the full long name of the File Location.</param>
 /// <returns>Word.Document Object</returns>
 public static Word.Document OpenWordDocument(Word.ApplicationClass WordApp, string FileLocation)
 {
     try
     {
         object j_FileName   = FileLocation;
         object j_Visible    = true;
         object j_ReadOnly   = false;
         object j_NullObject = System.Reflection.Missing.Value;
         // Let's open the document
         Word.Document WordDoc = WordApp.Documents.Open(ref j_FileName,
                                                        ref j_NullObject, ref j_ReadOnly, ref j_NullObject, ref j_NullObject,
                                                        ref j_NullObject, ref j_NullObject, ref j_NullObject, ref j_NullObject,
                                                        ref j_NullObject, ref j_NullObject, ref j_Visible);
         return(WordDoc);
     }
     catch (Exception e)
     {
         //show the user the error message
         MessageBox.Show(e.Message);
         return(null);
     }
 }
Exemple #23
0
        /// <summary>
        /// 删除word文档中相应的内容
        /// </summary>
        /// <param name="startText">起始字符</param>
        /// <param name="endText">终止字符</param>
        /// <param name="path">文档路径</param>
        /// <returns></returns>
        public bool DeleteText(string startText, string endText, string path)
        {
            object OBJpath = path;
            object missing = System.Reflection.Missing.Value;

            Word._Application wapp = new Word.ApplicationClass();
            Word.Document     wdoc = new Word.Document();
            wdoc = wapp.Documents.Open(ref OBJpath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

            Word.Selection tihuanwenzi = wapp.Selection;

            wapp.Options.ReplaceSelection      = true;
            wapp.Selection.Find.Forward        = true;
            wapp.Selection.Find.MatchWholeWord = true;
            object startstr = startText;
            object endstr   = endText;

            wapp.Selection.Find.ClearFormatting();
            wapp.Selection.Find.Execute(ref startstr, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            object start = wapp.Selection.Range.Start;//定位起始位置

            wapp.Selection.Find.ClearFormatting();
            wapp.Selection.Find.Execute(ref endstr, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            object end  = wapp.Selection.Range.End;//定义终止位置
            object unit = Type.Missing;

            object count = Type.Missing;

            wdoc.Range(ref start, ref end).Delete(ref unit, ref count);//删除操作
            object SaveChangs     = true;
            object OriginalFormat = System.Type.Missing;
            object RouteDocument  = System.Type.Missing;

            wapp.Documents.Close(ref missing, ref missing, ref missing);
            wapp.Quit(ref SaveChangs, ref OriginalFormat, ref RouteDocument);
            return(true);
        }
Exemple #24
0
        /// <summary>
        /// cover file word to body hmtl of mail,which embed fictures
        /// </summary>
        /// <param name="PathWordTemplate">path to word template file</param>
        /// <param name="Mail">Mail is embed body</param>
        /// <returns></returns>
        private static bool HTMLBody(DataSet DataFill, string PathWordTemplate, ref Email Mail)
        {
            string path = FrameworkParams.TEMP_FOLDER + @"\WordTemp";
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);
            path += PathWordTemplate.Substring(PathWordTemplate.LastIndexOf("\\"));
            WordDocument WordDoc = new WordDocument();
            try
            {
                WordDoc.Open(PathWordTemplate);
                for (int i = 0; i < DataFill.Tables.Count; i++)
                {
                    WordDoc.MailMerge.ExecuteGroup(DataFill.Tables[i]);
                }
                WordDoc.Save(path);

                Word.ApplicationClass wd = new Word.ApplicationClass();
                Word.Document document = new Word.Document();
                object fileName = (object)path;
                object newTemplate = false;
                object docType = 0;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;

                document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);

                object oFileName = (object)(path.Substring(0, path.LastIndexOf(".")) + ".html");
                object oSaveFormat = (object)(Word.WdSaveFormat.wdFormatHTML);

                if (System.IO.File.Exists(oFileName.ToString()))
                    System.IO.File.Delete(oFileName.ToString());

                document.SaveAs(ref oFileName,
                                ref oSaveFormat,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing,
                                ref missing);
                document.Close(ref missing, ref missing, ref missing);
                wd.Quit(ref missing, ref missing, ref missing);

                Mht mailbody = new Mht();
                mailbody.UnlockComponent("MHT-TEAMBEAN_1E1F4760821H");
                mailbody.UseCids = true;
                Mail = mailbody.GetEmail(oFileName.ToString());

                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// Loads a document into the control
        /// </summary>
        /// <param name="t_filename">path to the file (every type word can handle)</param>
        public void LoadDocument(string t_filename)
        {
            deactivateevents = true;
            filename         = t_filename;

            if (wd == null)
            {
                wd = new Word.ApplicationClass();
            }
            try
            {
                wd.CommandBars.AdaptiveMenus = false;
                wd.DocumentBeforeClose      += new Word.ApplicationEvents2_DocumentBeforeCloseEventHandler(OnClose);
                wd.NewDocument  += new Word.ApplicationEvents2_NewDocumentEventHandler(OnNewDoc);
                wd.DocumentOpen += new Word.ApplicationEvents2_DocumentOpenEventHandler(OnOpenDoc);
                wd.ApplicationEvents2_Event_Quit += new Word.ApplicationEvents2_QuitEventHandler(OnQuit);
            }
            catch { }

            if (document != null)
            {
                try
                {
                    object dummy = null;
                    wd.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch { }
            }

            if (wordWnd == 0)
            {
                wordWnd = FindWindow("Opusapp", null);
            }
            if (wordWnd != 0)
            {
                SetParent(wordWnd, this.Handle.ToInt32());

                object fileName    = filename;
                object newTemplate = false;
                object docType     = 0;
                object readOnly    = true;
                object isVisible   = true;
                object missing     = System.Reflection.Missing.Value;

                try
                {
                    if (wd == null)
                    {
                        throw new WordInstanceException();
                    }

                    if (wd.Documents == null)
                    {
                        throw new DocumentInstanceException();
                    }

                    if (wd != null && wd.Documents != null)
                    {
                        document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                    }

                    if (document == null)
                    {
                        throw new ValidDocumentException();
                    }
                }
                catch
                {
                }



                // =============================================================================================
                // Display for word property
                // =============================================================================================
                try
                {
                    wd.ActiveWindow.DisplayRightRuler        = true;
                    wd.ActiveWindow.DisplayScreenTips        = true;
                    wd.ActiveWindow.DisplayVerticalRuler     = true;
                    wd.ActiveWindow.DisplayRightRuler        = true;
                    wd.ActiveWindow.ActivePane.DisplayRulers = true;
                    wd.ActiveWindow.ActivePane.View.Type     = Word.WdViewType.wdWebView;
                    //wd.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;//wdWebView; // .wdNormalView;
                }
                catch
                {
                }

                /// Code Added
                /// Disable the specific buttons of the command bar
                /// By default, we disable/hide the menu bar
                /// The New/Open buttons of the command bar are disabled
                /// Other things can be added as required (and supported ..:) )
                /// Lots of commented code in here, if somebody needs to disable specific menu or sub-menu items.
                ///
                int counter = wd.ActiveWindow.Application.CommandBars.Count;
                for (int i = 1; i <= counter; i++)
                {
                    try
                    {
                        String nm = wd.ActiveWindow.Application.CommandBars[i].Name;
                        if (nm == "Standard")
                        {
                            //nm=i.ToString()+" "+nm;
                            //MessageBox.Show(nm);
                            int count_control = wd.ActiveWindow.Application.CommandBars[i].Controls.Count;
                            for (int j = 1; j <= 3; j++)
                            {
                                //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].ToString());
                                wd.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled = false;
                            }
                        }

                        if (nm == "Menu Bar")
                        {
                            //To disable the menubar, use the following (1) line
                            //wd.ActiveWindow.Application.CommandBars[i].Enabled=false;
                            for (int j = 1; j <= 6; j++)
                            {
                                ((Office.CommandBarPopup)wd.ActiveWindow.Application.CommandBars[i].Controls[1]).Controls[j].Enabled = false;
                            }
                            /// If you want to have specific menu or sub-menu items, write the code here.
                            /// Samples commented below

                            //							MessageBox.Show(nm);
                            //int count_control=wd.ActiveWindow.Application.CommandBars[i].Controls.Count;
                            //MessageBox.Show(count_control.ToString());

                            /*
                             *                          for(int j=1;j<=count_control;j++)
                             *                          {
                             *                                  /// The following can be used to disable specific menuitems in the menubar
                             *                                  /// wd.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled=false;
                             *
                             *                                  //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].ToString());
                             *                                  //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].Caption);
                             *                                  //MessageBox.Show(wd.ActiveWindow.Application.CommandBars[i].Controls[j].accChildCount.ToString());
                             *
                             *
                             *                                  ///The following can be used to disable some or all the sub-menuitems in the menubar
                             *
                             *
                             *                                  ////Office.CommandBarPopup c;
                             *                                  ////c = (Office.CommandBarPopup)wd.ActiveWindow.Application.CommandBars[i].Controls[j];
                             *                                  ////
                             *                                  ////for(int k=1;k<=c.Controls.Count;k++)
                             *                                  ////{
                             *                                  ////	//MessageBox.Show(k.ToString()+" "+c.Controls[k].Caption + " -- " + c.Controls[k].DescriptionText + " -- " );
                             *                                  ////	try
                             *                                  ////	{
                             *                                  ////		c.Controls[k].Enabled=false;
                             *                                  ////		c.Controls["Close Window"].Enabled=false;
                             *                                  ////	}
                             *                                  ////	catch
                             *                                  ////	{
                             *                                  ////
                             *                                  ////	}
                             *                                  ////}
                             *
                             *
                             *
                             *                                          //wd.ActiveWindow.Application.CommandBars[i].Controls[j].Control	 Controls[0].Enabled=false;
                             *                                  }
                             */
                        }

                        nm = "";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }



                // Show the word-document
                try
                {
                    wd.Visible = true;
                    wd.Activate();

                    SetWindowPos(wordWnd, this.Handle.ToInt32(), 0, 0, this.Bounds.Width, this.Bounds.Height, SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME | SWP_NOSIZE);

                    //Call onresize--I dont want to write the same lines twice
                    OnResize();
                }
                catch
                {
                    MessageBox.Show("Error: do not load the document into the control until the parent window is shown!");
                }

                /// We want to remove the system menu also. The title bar is not visible, but we want to avoid accidental minimize, maximize, etc ..by disabling the system menu(Alt+Space)
                try
                {
                    int hMenu = GetSystemMenu(wordWnd, false);
                    if (hMenu > 0)
                    {
                        int menuItemCount = GetMenuItemCount(hMenu);
                        RemoveMenu(hMenu, menuItemCount - 1, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 2, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 3, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 4, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 5, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 6, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 7, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 8, MF_REMOVE | MF_BYPOSITION);
                        DrawMenuBar(wordWnd);
                    }
                }
                catch { };



                this.Parent.Focus();
            }
            deactivateevents = false;
        }
Exemple #26
0
 private void OnQuit()
 {
     applicationClass = null;
 }
Exemple #27
0
        /// <summary>
        /// 删除word文档中相应的内容
        /// </summary>
        /// <param name="startText">起始字符</param>
        /// <param name="endText">终止字符</param>
        /// <param name="path">文档路径</param>
        /// <returns></returns>
        public bool DeleteText(string startText, string endText, string path)
        {
            object OBJpath = path;
            object missing = System.Reflection.Missing.Value;
            Word._Application wapp = new Word.ApplicationClass();
            Word.Document wdoc = new Word.Document();
            wdoc = wapp.Documents.Open(ref OBJpath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

            Word.Selection tihuanwenzi = wapp.Selection;

            wapp.Options.ReplaceSelection = true;
            wapp.Selection.Find.Forward = true;
            wapp.Selection.Find.MatchWholeWord = true;
            object startstr = startText;
            object endstr = endText;
            wapp.Selection.Find.ClearFormatting();
            wapp.Selection.Find.Execute(ref startstr, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            object start = wapp.Selection.Range.Start;//定位起始位置
            wapp.Selection.Find.ClearFormatting();
            wapp.Selection.Find.Execute(ref endstr, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            object end = wapp.Selection.Range.End;//定义终止位置
            object unit = Type.Missing;

            object count = Type.Missing;
            wdoc.Range(ref start, ref end).Delete(ref unit, ref count);//删除操作
            object SaveChangs = true;
            object OriginalFormat = System.Type.Missing;
            object RouteDocument = System.Type.Missing;
            wapp.Documents.Close(ref missing, ref missing, ref missing);
            wapp.Quit(ref SaveChangs, ref OriginalFormat, ref RouteDocument);
            return true;
        }
Exemple #28
0
        /// <summary>
        /// 打开指定的本地WORD病历文件
        /// </summary>
        /// <param name="szFilePath">本地路径</param>
        /// <returns>DataLayer.SystemData.ReturnValue</returns>
        public short OpenDocument(string szFilePath)
        {
            try
            {
                if (this.m_WordApp == null)
                    this.m_WordApp = new Word.ApplicationClass();
                this.m_WordApp.CommandBars.AdaptiveMenus = this.m_bShowInternalMenuStrip;
            }
            catch (Exception ex)
            {
                LogManager.Instance.WriteLog("WinWordControl.OpenDocument", ex);
                return SystemConst.ReturnValue.EXCEPTION;
            }

            this.CloseDocument();

            if (this.m_hWordWnd == IntPtr.Zero)
                this.m_hWordWnd = NativeMethods.User32.FindWindow("OpusApp", null);

            if (this.m_hWordWnd == IntPtr.Zero)
                return SystemConst.ReturnValue.FAILED;

            NativeMethods.User32.SetParent(this.m_hWordWnd, this.Handle);

            try
            {
                if (this.m_WordApp == null || this.m_WordApp.Documents == null)
                    return SystemConst.ReturnValue.FAILED;

                object fileName = szFilePath;
                object newTemplate = false;
                object docType = Word.WdDocumentType.wdTypeDocument;
                object isVisible = true;
                this.m_WordDoc = this.m_WordApp.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
            }
            catch (Exception ex)
            {
                LogManager.Instance.WriteLog("WinWordControl.OpenDocument", ex);
                return SystemConst.ReturnValue.EXCEPTION;
            }
            this.ResumeLayout();
               this.Activate();

            try
            {
                this.HandleWordUILayout();
            }
            catch (Exception ex)
            {
                LogManager.Instance.WriteLog("WinWordControl.OpenDocument", ex);
            }
            return SystemConst.ReturnValue.OK;
        }
Exemple #29
0
        /// <summary>
        /// 打开指定的本地WORD病历文件
        /// </summary>
        /// <param name="szFilePath">本地路径</param>
        /// <returns>DataLayer.SystemData.ReturnValue</returns>
        public short OpenDocument(string szFilePath)
        {
            try
            {
                if (this.m_WordApp == null)
                {
                    this.m_WordApp = new Word.ApplicationClass();
                }
                this.m_WordApp.CommandBars.AdaptiveMenus = this.m_bShowInternalMenuStrip;
            }
            catch (Exception ex)
            {
                LogManager.Instance.WriteLog("WinWordControl.OpenDocument", ex);
                return(SystemConst.ReturnValue.EXCEPTION);
            }

            this.CloseDocument();

            if (this.m_hWordWnd == IntPtr.Zero)
            {
                this.m_hWordWnd = NativeMethods.User32.FindWindow("OpusApp", null);
            }

            if (this.m_hWordWnd == IntPtr.Zero)
            {
                return(SystemConst.ReturnValue.FAILED);
            }

            NativeMethods.User32.SetParent(this.m_hWordWnd, this.Handle);

            try
            {
                if (this.m_WordApp == null || this.m_WordApp.Documents == null)
                {
                    return(SystemConst.ReturnValue.FAILED);
                }

                object fileName    = szFilePath;
                object newTemplate = false;
                object docType     = Word.WdDocumentType.wdTypeDocument;
                object isVisible   = true;
                this.m_WordDoc = this.m_WordApp.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
            }
            catch (Exception ex)
            {
                LogManager.Instance.WriteLog("WinWordControl.OpenDocument", ex);
                return(SystemConst.ReturnValue.EXCEPTION);
            }
            this.ResumeLayout();
            this.Activate();

            try
            {
                this.HandleWordUILayout();
            }
            catch (Exception ex)
            {
                LogManager.Instance.WriteLog("WinWordControl.OpenDocument", ex);
            }
            return(SystemConst.ReturnValue.OK);
        }
Exemple #30
0
 public void PreActivate()
 {
     if (applicationClass == null) applicationClass = new Word.ApplicationClass();
 }
Exemple #31
0
        private void but_Table_Click(object sender, EventArgs e)
        {
            object Nothing = System.Reflection.Missing.Value;
            object missing = System.Reflection.Missing.Value;

            //创建Word文档
            Word.Application wordApp = new Word.ApplicationClass();
            Word.Document    wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            wordApp.Visible = true;

            //设置文档宽度
            wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse("2"));
            wordApp.ActiveWindow.ActivePane.HorizontalPercentScrolled = 11;
            wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2"));

            Object start = Type.Missing;
            Object end   = Type.Missing;

            PictureBox pp = new PictureBox();   //新建一个PictureBox控件
            int        p1 = 0;

            for (int i = 0; i < MyDS_Grid.Tables[0].Rows.Count; i++)
            {
                try
                {
                    byte[]       pic = (byte[])(MyDS_Grid.Tables[0].Rows[i][23]); //将数据库中的图片转换成二进制流
                    MemoryStream ms  = new MemoryStream(pic);                     //将字节数组存入到二进制流中
                    pp.Image = Image.FromStream(ms);                              //二进制流Image控件中显示
                    pp.Image.Save(@"C:\22.bmp");                                  //将图片存入到指定的路径
                }
                catch
                {
                    p1 = 1;
                }
                object rng     = Type.Missing;
                string strInfo = "职工基本信息表" + "(" + MyDS_Grid.Tables[0].Rows[i][1].ToString() + ")";
                start = 0;
                end   = 0;
                wordDoc.Range(ref start, ref end).InsertBefore(strInfo);                                                        //插入文本
                wordDoc.Range(ref start, ref end).Font.Name = "Verdana";                                                        //设置字体
                wordDoc.Range(ref start, ref end).Font.Size = 20;                                                               //设置字体大小
                wordDoc.Range(ref start, ref end).ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //设置字体局中

                start = strInfo.Length;
                end   = strInfo.Length;
                wordDoc.Range(ref start, ref end).InsertParagraphAfter();//插入回车

                object     missingValue = Type.Missing;
                object     location     = strInfo.Length; //如果location超过已有字符的长度将会出错。一定要比"明细表"串多一个字符
                Word.Range rng2         = wordDoc.Range(ref location, ref location);

                wordDoc.Tables.Add(rng2, 14, 6, ref missingValue, ref missingValue);
                wordDoc.Tables.Item(1).Rows.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
                wordDoc.Tables.Item(1).Rows.Height     = wordApp.CentimetersToPoints(float.Parse("0.8"));
                wordDoc.Tables.Item(1).Range.Font.Size = 10;
                wordDoc.Tables.Item(1).Range.Font.Name = "宋体";

                //设置表格样式
                wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
                wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
                wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).Color     = Word.WdColor.wdColorAutomatic;
                wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐

                //第5行显示
                wordDoc.Tables.Item(1).Cell(1, 5).Merge(wordDoc.Tables.Item(1).Cell(5, 6));
                //第6行显示
                wordDoc.Tables.Item(1).Cell(6, 5).Merge(wordDoc.Tables.Item(1).Cell(6, 6));
                //第9行显示
                wordDoc.Tables.Item(1).Cell(9, 4).Merge(wordDoc.Tables.Item(1).Cell(9, 6));
                //第12行显示
                wordDoc.Tables.Item(1).Cell(12, 2).Merge(wordDoc.Tables.Item(1).Cell(12, 6));
                //第13行显示
                wordDoc.Tables.Item(1).Cell(13, 2).Merge(wordDoc.Tables.Item(1).Cell(13, 6));
                //第14行显示
                wordDoc.Tables.Item(1).Cell(14, 2).Merge(wordDoc.Tables.Item(1).Cell(14, 6));

                //第1行赋值
                wordDoc.Tables.Item(1).Cell(1, 1).Range.Text = "职工编号:";
                wordDoc.Tables.Item(1).Cell(1, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][0].ToString();
                wordDoc.Tables.Item(1).Cell(1, 3).Range.Text = "职工姓名:";
                wordDoc.Tables.Item(1).Cell(1, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][1].ToString();

                //插入图片

                if (p1 == 0)
                {
                    string FileName         = @"C:\22.bmp";//图片所在路径
                    object LinkToFile       = false;
                    object SaveWithDocument = true;
                    object Anchor           = wordDoc.Tables.Item(1).Cell(1, 5).Range; //指定图片插入的区域
                    //将图片插入到单元格中
                    wordDoc.Tables.Item(1).Cell(1, 5).Range.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
                }
                p1 = 0;

                //第2行赋值
                wordDoc.Tables.Item(1).Cell(2, 1).Range.Text = "民族类别:";
                wordDoc.Tables.Item(1).Cell(2, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][2].ToString();
                wordDoc.Tables.Item(1).Cell(2, 3).Range.Text = "出生日期:";
                try
                {
                    wordDoc.Tables.Item(1).Cell(2, 4).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Tables[0].Rows[i][3]).ToShortDateString());
                }
                catch { wordDoc.Tables.Item(1).Cell(2, 4).Range.Text = ""; }
                //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][3]);
                //第3行赋值
                wordDoc.Tables.Item(1).Cell(3, 1).Range.Text = "年龄:";
                wordDoc.Tables.Item(1).Cell(3, 2).Range.Text = Convert.ToString(MyDS_Grid.Tables[0].Rows[i][4]);
                wordDoc.Tables.Item(1).Cell(3, 3).Range.Text = "文化程序:";
                wordDoc.Tables.Item(1).Cell(3, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][5].ToString();
                //第4行赋值
                wordDoc.Tables.Item(1).Cell(4, 1).Range.Text = "婚姻:";
                wordDoc.Tables.Item(1).Cell(4, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][6].ToString();
                wordDoc.Tables.Item(1).Cell(4, 3).Range.Text = "性别:";
                wordDoc.Tables.Item(1).Cell(4, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][7].ToString();
                //第5行赋值
                wordDoc.Tables.Item(1).Cell(5, 1).Range.Text = "政治面貌:";
                wordDoc.Tables.Item(1).Cell(5, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][8].ToString();
                wordDoc.Tables.Item(1).Cell(5, 3).Range.Text = "单位工作时间:";
                try
                {
                    wordDoc.Tables.Item(1).Cell(5, 4).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Tables[0].Rows[0][10]).ToShortDateString());
                }
                catch { wordDoc.Tables.Item(1).Cell(5, 4).Range.Text = ""; }
                //第6行赋值
                wordDoc.Tables.Item(1).Cell(6, 1).Range.Text = "籍贯:";
                wordDoc.Tables.Item(1).Cell(6, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][24].ToString();
                wordDoc.Tables.Item(1).Cell(6, 3).Range.Text = MyDS_Grid.Tables[0].Rows[i][25].ToString();
                wordDoc.Tables.Item(1).Cell(6, 4).Range.Text = "身份证:";
                wordDoc.Tables.Item(1).Cell(6, 5).Range.Text = MyDS_Grid.Tables[0].Rows[i][9].ToString();
                //第7行赋值
                wordDoc.Tables.Item(1).Cell(7, 1).Range.Text = "工龄:";
                wordDoc.Tables.Item(1).Cell(7, 2).Range.Text = Convert.ToString(MyDS_Grid.Tables[0].Rows[i][11]);
                wordDoc.Tables.Item(1).Cell(7, 3).Range.Text = "职工类别:";
                wordDoc.Tables.Item(1).Cell(7, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][12].ToString();
                wordDoc.Tables.Item(1).Cell(7, 5).Range.Text = "职务类别:";
                wordDoc.Tables.Item(1).Cell(7, 6).Range.Text = MyDS_Grid.Tables[0].Rows[i][13].ToString();
                //第8行赋值
                wordDoc.Tables.Item(1).Cell(8, 1).Range.Text = "工资类别:";
                wordDoc.Tables.Item(1).Cell(8, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][14].ToString();
                wordDoc.Tables.Item(1).Cell(8, 3).Range.Text = "部门类别:";
                wordDoc.Tables.Item(1).Cell(8, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][15].ToString();
                wordDoc.Tables.Item(1).Cell(8, 5).Range.Text = "职称类别:";
                wordDoc.Tables.Item(1).Cell(8, 6).Range.Text = MyDS_Grid.Tables[0].Rows[i][16].ToString();
                //第9行赋值
                wordDoc.Tables.Item(1).Cell(9, 1).Range.Text = "月工资:";
                wordDoc.Tables.Item(1).Cell(9, 2).Range.Text = Convert.ToString(MyDS_Grid.Tables[0].Rows[i][26]);
                wordDoc.Tables.Item(1).Cell(9, 3).Range.Text = "银行帐号:";
                wordDoc.Tables.Item(1).Cell(9, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][27].ToString();
                //第10行赋值
                wordDoc.Tables.Item(1).Cell(10, 1).Range.Text = "合同起始日期:";
                try
                {
                    wordDoc.Tables.Item(1).Cell(10, 2).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Tables[0].Rows[i][28]).ToShortDateString());
                }
                catch { wordDoc.Tables.Item(1).Cell(10, 2).Range.Text = ""; }
                //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][28]);
                wordDoc.Tables.Item(1).Cell(10, 3).Range.Text = "合同结束日期:";
                try
                {
                    wordDoc.Tables.Item(1).Cell(10, 4).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Tables[0].Rows[i][29]).ToShortDateString());
                }
                catch { wordDoc.Tables.Item(1).Cell(10, 4).Range.Text = ""; }
                //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][29]);
                wordDoc.Tables.Item(1).Cell(10, 5).Range.Text = "合同年限:";
                wordDoc.Tables.Item(1).Cell(10, 6).Range.Text = Convert.ToString(MyDS_Grid.Tables[0].Rows[i][30]);
                //第11行赋值
                wordDoc.Tables.Item(1).Cell(11, 1).Range.Text = "电话:";
                wordDoc.Tables.Item(1).Cell(11, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][17].ToString();
                wordDoc.Tables.Item(1).Cell(11, 3).Range.Text = "手机:";
                wordDoc.Tables.Item(1).Cell(11, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][18].ToString();
                wordDoc.Tables.Item(1).Cell(11, 5).Range.Text = "毕业时间:";
                try
                {
                    wordDoc.Tables.Item(1).Cell(11, 6).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Tables[0].Rows[i][21]).ToShortDateString());
                }
                catch { wordDoc.Tables.Item(1).Cell(11, 6).Range.Text = ""; }
                //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][21]);
                //第12行赋值
                wordDoc.Tables.Item(1).Cell(12, 1).Range.Text = "毕业学校:";
                wordDoc.Tables.Item(1).Cell(12, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][19].ToString();
                //第13行赋值
                wordDoc.Tables.Item(1).Cell(13, 1).Range.Text = "主修专业:";
                wordDoc.Tables.Item(1).Cell(13, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][20].ToString();
                //第14行赋值
                wordDoc.Tables.Item(1).Cell(14, 1).Range.Text = "家庭地址:";
                wordDoc.Tables.Item(1).Cell(14, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][22].ToString();

                wordDoc.Range(ref start, ref end).InsertParagraphAfter();                                                       //插入回车
                wordDoc.Range(ref start, ref end).ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //设置字体局中
            }
        }
Exemple #32
0
        private Word.Document oDoc;                             // a reference to the document

//        public InvokeControlMemberDelegate ojbInvokeControlMember;

        public CCWordApp()
        {
            // activate the interface with the COM object of Microsoft Word
            oWordApplic = new Word.ApplicationClass();
        }
Exemple #33
0
 private void OnQuit()
 {
     applicationClass = null;
 }
Exemple #34
0
 public void InsertFile(string path)
 {
     Word.ApplicationClass applicationClass = new Word.ApplicationClass();
     object fileName = showPath;
     Word.Document doct = applicationClass.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
     doct.Activate();
     object confirmConversion = false;
     object link = false;
     object attachment = false;
     applicationClass.Selection.InsertFile(path, ref missing, ref confirmConversion, ref link, ref attachment);
     object pBreak = (int)Word.WdBreakType.wdPageBreak;
     applicationClass.Selection.InsertBreak(ref pBreak);
     doct.SaveAs(ref   fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
     ((Word._Document)doct).Close(ref missing, ref missing, ref missing);
 }
Exemple #35
0
 public bool Replace(string strOldText, string strNewText, string path)
 {
     object missing = System.Reflection.Missing.Value;
     Word._Application wapp = new Word.ApplicationClass();
     wapp.Visible = false;
     object OBJpath = path;
     object text1 = strOldText;
     object text2 = strNewText;
     object Replace = Word.WdReplace.wdReplaceAll;
     wapp.Documents.Open(ref OBJpath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
     wapp.Selection.Find.Execute(ref text1, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref text2, ref Replace, ref missing, ref missing, ref missing, ref missing);
     object SaveChangs = true;
     object OriginalFormat = System.Type.Missing;
     object RouteDocument = System.Type.Missing;
     wapp.Quit(ref SaveChangs, ref OriginalFormat, ref RouteDocument);
     return true;
 }
Exemple #36
0
        public void RunMicrosoftWord()
        {
            if (wd != null)
            {
                ExitMicrosoftWord();
            }

            if (wd == null)
            {
                wd = new Word.ApplicationClass();
            }
        }
Exemple #37
0
        private Word.ApplicationClass oWordApplic; // a reference to Word application

        #endregion Fields

        #region Constructors

        public CCWordApp()
        {
            // activate the interface with the COM object of Microsoft Word
            oWordApplic = new Word.ApplicationClass();
        }
Exemple #38
0
 public void CloseWordApplication()
 {
     try
     {
         object saveChanges = false;
         object originalFormat = null;
         object routeDocument = null;
         if (this.m_WordApp != null)
             this.m_WordApp.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
         this.m_WordApp = null;
         this.m_hWordWnd = IntPtr.Zero;
     }
     catch (Exception ex)
     {
         LogManager.Instance.WriteLog("WinWordControl.CloseWordApplication", ex);
     }
 }
Exemple #39
0
        /// <summary>
        /// Close the current Document in the control --> you can 
        /// load a new one with LoadDocument
        /// </summary>
        public void ExitMicrosoftWord()
        {
            if (wd == null) return;
            try
            {
                deactivateevents = true;

                object dummy = null;
                object dummy2 = (object)false;
                document.Close(ref dummy, ref dummy, ref dummy);
                // Change the line below.
                wd.Quit(ref dummy2, ref dummy, ref dummy);

                deactivateevents = false;
            }
            catch (Exception ex)
            {
                //String strErr = ex.Message;
            }
            finally
            {
                this.document = null;
                this.wordWnd = 0;
                wd = null;
            }
        }
Exemple #40
0
        public void CreateWord(string pFileName)
        {
            deactivateevents = true;
            FileName         = pFileName;
            if (WordApplication == null)
            {
                WordApplication = new Word.ApplicationClass();
            }
            try
            {
                WordApplication.CommandBars.AdaptiveMenus = false;
                WordApplication.DocumentBeforeClose      += new Word.ApplicationEvents2_DocumentBeforeCloseEventHandler(OnClose);
                WordApplication.NewDocument  += new Word.ApplicationEvents2_NewDocumentEventHandler(OnNewDoc);
                WordApplication.DocumentOpen += new Word.ApplicationEvents2_DocumentOpenEventHandler(OnOpenDoc);
                WordApplication.ApplicationEvents2_Event_Quit += new Word.ApplicationEvents2_QuitEventHandler(OnQuit);
            }
            catch { }

            if (WordDoc != null)
            {
                try
                {
                    object dummy = null;
                    WordApplication.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch { }
            }

            if (WordWnd == 0)
            {
                WordWnd = FindWindow("Opusapp", null);
            }
            if (WordWnd != 0)
            {
                SetParent(WordWnd, this.plApplyName.Handle.ToInt32());

                object fileName    = FileName;
                object newTemplate = false;
                object docType     = 0;
                object readOnly    = true;
                object isVisible   = true;
                object missing     = System.Reflection.Missing.Value;

                try
                {
                    if (WordApplication == null)
                    {
                        throw new WordInstanceException();
                    }

                    if (WordApplication.Documents == null)
                    {
                        throw new DocumentInstanceException();
                    }

                    if (WordApplication != null && WordApplication.Documents != null)
                    {
                        WordDoc = WordApplication.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                    }

                    if (WordDoc == null)
                    {
                        throw new ValidDocumentException();
                    }
                }
                catch
                {
                }

                try
                {
                    WordApplication.ActiveWindow.DisplayRightRuler        = false;
                    WordApplication.ActiveWindow.DisplayScreenTips        = false;
                    WordApplication.ActiveWindow.DisplayVerticalRuler     = false;
                    WordApplication.ActiveWindow.DisplayRightRuler        = false;
                    WordApplication.ActiveWindow.ActivePane.DisplayRulers = false;
                    WordApplication.ActiveWindow.ActivePane.View.Type     = Word.WdViewType.wdWebView;
                }
                catch { }
                int counter = WordApplication.ActiveWindow.Application.CommandBars.Count;
                for (int i = 1; i <= counter; i++)
                {
                    try
                    {
                        String nm = WordApplication.ActiveWindow.Application.CommandBars[i].Name;
                        if (nm == "Standard")
                        {
                            int count_control = WordApplication.ActiveWindow.Application.CommandBars[i].Controls.Count;
                            for (int j = 1; j <= 2; j++)
                            {
                                WordApplication.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled = false;
                            }
                        }

                        if (nm == "Menu Bar")
                        {
                            //To disable the menubar, use the following (1) line
                            WordApplication.ActiveWindow.Application.CommandBars[i].Enabled = false;
                        }

                        nm = "";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }



                // Show the word-document
                try
                {
                    WordApplication.Visible = true;
                    WordApplication.Activate();

                    SetWindowPos(WordWnd, this.plApplyName.Handle.ToInt32(), 0, 0, this.Bounds.Width, this.Bounds.Height, SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME | SWP_NOSIZE);

                    //Call onresize--I dont want to write the same lines twice
                    //OnResize();
                }
                catch
                {
                    MessageBox.Show("Error: do not load the document into the control until the parent window is shown!");
                }
                /// We want to remove the system menu also. The title bar is not visible, but we want to avoid accidental minimize, maximize, etc ..by disabling the system menu(Alt+Space)
                try
                {
                    int hMenu = GetSystemMenu(WordWnd, false);
                    if (hMenu > 0)
                    {
                        int menuItemCount = GetMenuItemCount(hMenu);
                        RemoveMenu(hMenu, menuItemCount - 1, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 2, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 3, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 4, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 5, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 6, MF_REMOVE | MF_BYPOSITION);
                        DrawMenuBar(WordWnd);
                    }
                }
                catch { }
                if (this.Parent != null)
                {
                    this.Parent.Focus();
                }
            }
            deactivateevents = false;
        }
Exemple #41
0
        public void LoadDocument(string t_filename)
        {
            deactivateevents = true;
            filename         = t_filename;

            if (applicationClass == null)
            {
                applicationClass = new Word.ApplicationClass();
            }
            try
            {
                applicationClass.CommandBars.AdaptiveMenus = false;
                applicationClass.DocumentBeforeClose      += new Word.ApplicationEvents2_DocumentBeforeCloseEventHandler(OnClose);
                applicationClass.NewDocument  += new Word.ApplicationEvents2_NewDocumentEventHandler(OnNewDoc);
                applicationClass.DocumentOpen += new Word.ApplicationEvents2_DocumentOpenEventHandler(OnOpenDoc);
                applicationClass.ApplicationEvents2_Event_Quit += new Word.ApplicationEvents2_QuitEventHandler(OnQuit);
            }
            catch { }



            if (document != null)
            {
                try
                {
                    object dummy = null;
                    applicationClass.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch { }
            }

            if (wordWnd == 0)
            {
                wordWnd = FindWindow("Opusapp", null);
            }
            if (wordWnd != 0)
            {
                SetParent(wordWnd, this.Handle.ToInt32());

                object fileName    = filename;
                object newTemplate = false;
                object docType     = 0;
                object readOnly    = true;
                object isVisible   = true;
                object missing     = System.Reflection.Missing.Value;


                try
                {
                    if (applicationClass == null)
                    {
                        throw new WordInstanceException();
                    }

                    if (applicationClass.Documents == null)
                    {
                        throw new DocumentInstanceException();
                    }

                    if (applicationClass != null && applicationClass.Documents != null)
                    {
                        document = applicationClass.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                    }

                    if (document == null)
                    {
                        throw new ValidDocumentException();
                    }
                }
                catch
                {
                }

                try
                {
                    applicationClass.ActiveWindow.DisplayRightRuler        = false;
                    applicationClass.ActiveWindow.DisplayScreenTips        = false;
                    applicationClass.ActiveWindow.DisplayVerticalRuler     = false;
                    applicationClass.ActiveWindow.DisplayRightRuler        = false;
                    applicationClass.ActiveWindow.ActivePane.DisplayRulers = false;
                    applicationClass.ActiveWindow.ActivePane.View.Type     = Word.WdViewType.wdWebView;
                    //wd.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;//wdWebView; // .wdNormalView;
                }
                catch
                {
                }
                int counter = applicationClass.ActiveWindow.Application.CommandBars.Count;
                for (int i = 1; i <= counter; i++)
                {
                    try
                    {
                        String nm = applicationClass.ActiveWindow.Application.CommandBars[i].Name;
                        if (nm == "Standard")
                        {
                            int count_control = applicationClass.ActiveWindow.Application.CommandBars[i].Controls.Count;
                            for (int j = 1; j <= 2; j++)
                            {
                                applicationClass.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled = false;
                            }
                        }

                        if (nm == "Menu Bar")
                        {
                            applicationClass.ActiveWindow.Application.CommandBars[i].Enabled = false;
                        }

                        nm = "";
                    }
                    catch
                    {
                        //MessageBox.Show(ex.ToString());
                    }
                }



                try
                {
                    applicationClass.Visible = true;
                    applicationClass.Activate();

                    SetWindowPos(wordWnd, this.Handle.ToInt32(), 0, 0, this.Bounds.Width, this.Bounds.Height, SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME | SWP_NOSIZE);
                    OnResize();
                    this.GetWordContentHeight(wordWnd);
                }
                catch
                {
                    MessageBox.Show("Error: do not load the document into the control until the parent window is shown!");
                }


                try
                {
                    int hMenu = GetSystemMenu(wordWnd, false);
                    if (hMenu > 0)
                    {
                        int menuItemCount = GetMenuItemCount(hMenu);
                        RemoveMenu(hMenu, menuItemCount - 1, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 2, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 3, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 4, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 5, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 6, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 7, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 8, MF_REMOVE | MF_BYPOSITION);
                        DrawMenuBar(wordWnd);
                    }
                }
                catch { };



                this.Parent.Focus();
            }
            deactivateevents = false;
        }
        /// <summary>
        /// Loads a document into the control
        /// </summary>
        /// <param name="t_filename">path to the file (every type word can handle)</param>
        public void LoadDocument(string t_filename)
        {
            deactivateevents = true;
            filename = t_filename;

            if(wd == null) wd = new Word.ApplicationClass();
            try
            {
                wd.CommandBars.AdaptiveMenus = false;
                wd.DocumentBeforeClose += new Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(OnClose);
                //wd.OnNewDocument += new Word.ApplicationEvents4_NewDocumentEventHandler(OnNewDoc);
                wd.DocumentOpen+= new Word.ApplicationEvents4_DocumentOpenEventHandler(OnOpenDoc);
                wd.ApplicationEvents2_Event_Quit += new Word.ApplicationEvents2_QuitEventHandler(OnQuit);
            }
            catch{}

            if(document != null)
            {
                try
                {
                    object dummy=null;
                    wd.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch{}
            }

            if( wordWnd==0 ) wordWnd = FindWindow( "Opusapp", null);
            if (wordWnd!=0)
            {
                SetParent( wordWnd, this.Handle.ToInt32());

                object fileName = filename;
                object newTemplate = false;
                object docType = 0;
                object readOnly = true;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;

                try
                {
                    if( wd == null )
                    {
                        throw new WordInstanceException();
                    }

                    if( wd.Documents == null )
                    {
                        throw new DocumentInstanceException();
                    }

                    if( wd != null && wd.Documents != null )
                    {
                        document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                    }

                    if(document == null)
                    {
                        throw new ValidDocumentException();
                    }
                }
                catch
                {
                }

                try
                {
                    wd.ActiveWindow.DisplayRightRuler=false;
                    wd.ActiveWindow.DisplayScreenTips=false;
                    wd.ActiveWindow.DisplayVerticalRuler=false;
                    wd.ActiveWindow.DisplayRightRuler=false;
                    wd.ActiveWindow.ActivePane.DisplayRulers=false;
                    wd.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdWebView; // .wdNormalView;
                }
                catch
                {

                }

                /*
                int counter = wd.ActiveWindow.Application.CommandBars.Count;
                for(int i = 0; i < counter;i++)
                {
                    try
                    {
                        wd.ActiveWindow.Application.CommandBars[i].Enabled=false;
                    }
                    catch
                    {

                    }
                }
                */
                try
                {
                    wd.Visible = true;
                    wd.Activate();

                    SetWindowPos(wordWnd,this.Handle.ToInt32(),0,0,this.Bounds.Width+20,this.Bounds.Height+20, SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME);
                    MoveWindow(wordWnd,-5,-33,this.Bounds.Width+10,this.Bounds.Height+57,true);
                }
                catch
                {
                    MessageBox.Show("Error: do not load the document into the control until the parent window is shown!");
                }
                this.Parent.Focus();

            }
            deactivateevents = false;
        }
 /// <summary>
 /// Preactivation
 /// It's usefull, if you need more speed in the main Program
 /// so you can preload Word.
 /// </summary>
 public void PreActivate()
 {
     if(wd == null) wd = new Word.ApplicationClass();
 }
 /// <summary>
 /// catches Word's quit event
 /// normally it should not fire, but just to be shure
 /// safely release the internal Word Instance 
 /// </summary>
 private void OnQuit()
 {
     wd=null;
 }
		/// <summary>
		/// Loads a document into the control
		/// </summary>
		/// <param name="t_filename">path to the file (every type word can handle)</param>
		public void LoadDocument(string t_filename)
		{
			deactivateevents = true;
			filename = t_filename;
		
			if(wd == null) wd = new Word.ApplicationClass();
			try 
			{
				wd.CommandBars.AdaptiveMenus = false;
                
				wd.DocumentBeforeClose +=new  Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(OnClose);
                //wd.NewDocument += new Word.ApplicationEvents3_NewDocumentEventHandler(OnNewDoc);  
                   // new Word.ApplicationEvents4_NewDocumentEventHandler(OnNewDoc);
				wd.DocumentOpen+= new Word.ApplicationEvents4_DocumentOpenEventHandler(OnOpenDoc);

				wd.ApplicationEvents2_Event_Quit+=new Word.ApplicationEvents2_QuitEventHandler(OnQuit);
        
			}
			catch{}

			if(document != null) 
			{
				try
				{
					object dummy=null;
					wd.Documents.Close(ref dummy, ref dummy, ref dummy);
				}
				catch{}
			}

			if( wordWnd==0 ) wordWnd = FindWindow( "Opusapp", null);
			if (wordWnd!=0)
			{
				SetParent( wordWnd, this.Handle.ToInt32());				
			
				object fileName = filename;
				object newTemplate = false;
				object docType = 0;
				object readOnly = true;
				object isVisible = true;
				object missing = System.Reflection.Missing.Value;
			
				try
				{
					if( wd == null )
					{
						throw new WordInstanceException();
					}

					if( wd.Documents == null )
					{
						throw new DocumentInstanceException();
					}
				
					if( wd != null && wd.Documents != null )
					{
						document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
					}
							
					if(document == null)
					{
						throw new ValidDocumentException();
					}
				}
				catch
				{
				}

				try
				{
					wd.ActiveWindow.DisplayRightRuler=false;
					wd.ActiveWindow.DisplayScreenTips=false;
					wd.ActiveWindow.DisplayVerticalRuler=false;
					wd.ActiveWindow.DisplayRightRuler=false;
					wd.ActiveWindow.ActivePane.DisplayRulers=false;
					wd.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdWebView; // .wdNormalView;
				}
				catch
				{

				}

				int counter = wd.ActiveWindow.Application.CommandBars.Count;
				for(int i = 0; i < counter;i++)
				{
					try
					{
						wd.ActiveWindow.Application.CommandBars[i].Enabled=false;
					}
					catch
					{

					}
				}
				try
				{
					wd.Visible = true;
					wd.Activate();
				
					SetWindowPos(wordWnd,this.Handle.ToInt32(),0,0,this.Bounds.Width+20,this.Bounds.Height+20, SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME);
					MoveWindow(wordWnd,-5,-33,this.Bounds.Width+10,this.Bounds.Height+57,true);
				}
				catch
				{
					MessageBox.Show("Error: do not load the document into the control until the parent window is shown!");
				}
				this.Parent.Focus();
				
			}
			deactivateevents = false;
		}
Exemple #46
0
        public void LoadDocument(string t_filename)
        {
            deactivateevents = true;
            filename = t_filename;

            if (applicationClass == null) applicationClass = new Word.ApplicationClass();
            try
            {
                applicationClass.CommandBars.AdaptiveMenus = false;
                applicationClass.DocumentBeforeClose += new Word.ApplicationEvents2_DocumentBeforeCloseEventHandler(OnClose);
                applicationClass.NewDocument += new Word.ApplicationEvents2_NewDocumentEventHandler(OnNewDoc);
                applicationClass.DocumentOpen += new Word.ApplicationEvents2_DocumentOpenEventHandler(OnOpenDoc);
                applicationClass.ApplicationEvents2_Event_Quit += new Word.ApplicationEvents2_QuitEventHandler(OnQuit);

            }
            catch { }

            if (document != null)
            {
                try
                {
                    object dummy = null;
                    applicationClass.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch { }
            }

            if (wordWnd == 0) wordWnd = FindWindow("Opusapp", null);
            if (wordWnd != 0)
            {
                SetParent(wordWnd, this.Handle.ToInt32());

                object fileName = filename;
                object newTemplate = false;
                object docType = 0;
                object readOnly = true;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;

                try
                {
                    if (applicationClass == null)
                    {
                        throw new WordInstanceException();
                    }

                    if (applicationClass.Documents == null)
                    {
                        throw new DocumentInstanceException();
                    }

                    if (applicationClass != null && applicationClass.Documents != null)
                    {
                        document = applicationClass.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                    }

                    if (document == null)
                    {
                        throw new ValidDocumentException();
                    }
                }
                catch
                {
                }

                try
                {
                    applicationClass.ActiveWindow.DisplayRightRuler = false;
                    applicationClass.ActiveWindow.DisplayScreenTips = false;
                    applicationClass.ActiveWindow.DisplayVerticalRuler = false;
                    applicationClass.ActiveWindow.DisplayRightRuler = false;
                    applicationClass.ActiveWindow.ActivePane.DisplayRulers = false;
                    applicationClass.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdWebView;
                    //wd.ActiveWindow.ActivePane.View.Type = Word.WdViewType.wdPrintView;//wdWebView; // .wdNormalView;
                }
                catch
                {

                }
                int counter = applicationClass.ActiveWindow.Application.CommandBars.Count;
                for (int i = 1; i <= counter; i++)
                {
                    try
                    {

                        String nm = applicationClass.ActiveWindow.Application.CommandBars[i].Name;
                        if (nm == "Standard")
                        {
                            int count_control = applicationClass.ActiveWindow.Application.CommandBars[i].Controls.Count;
                            for (int j = 1; j <= 2; j++)
                            {
                                applicationClass.ActiveWindow.Application.CommandBars[i].Controls[j].Enabled = false;
                            }
                        }

                        if (nm == "Menu Bar")
                        {
                            applicationClass.ActiveWindow.Application.CommandBars[i].Enabled = false;
                        }

                        nm = "";
                    }
                    catch
                    {
                        //MessageBox.Show(ex.ToString());
                    }
                }

                try
                {
                    applicationClass.Visible = true;
                    applicationClass.Activate();

                    SetWindowPos(wordWnd, this.Handle.ToInt32(), 0, 0, this.Bounds.Width, this.Bounds.Height, SWP_NOZORDER | SWP_NOMOVE | SWP_DRAWFRAME | SWP_NOSIZE);
                    OnResize();
                    this.GetWordContentHeight(wordWnd);

                }
                catch
                {
                    MessageBox.Show("Error: do not load the document into the control until the parent window is shown!");
                }

                try
                {
                    int hMenu = GetSystemMenu(wordWnd, false);
                    if (hMenu > 0)
                    {
                        int menuItemCount = GetMenuItemCount(hMenu);
                        RemoveMenu(hMenu, menuItemCount - 1, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 2, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 3, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 4, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 5, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 6, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 7, MF_REMOVE | MF_BYPOSITION);
                        RemoveMenu(hMenu, menuItemCount - 8, MF_REMOVE | MF_BYPOSITION);
                        DrawMenuBar(wordWnd);
                    }
                }
                catch { };

                this.Parent.Focus();

            }
            deactivateevents = false;
        }