/// <summary> /// Function uses Word app to activate word window. /// </summary> /// <param name="docUri"></param> /// <returns></returns> internal static bool FocusDocumentApp(string docUri) { if (WordApp != null) { Document doc = WordApp.Documents[docUri]; using (var win = new WindowWrapper(doc.ActiveWindow)) { win.Activate(); win.SetFocus(); win.WindowState = WdWindowState.wdWindowStateNormal; WordApp.Activate(); } } return(false); }
/// <summary> /// Sets the application tag visibility state. /// </summary> /// <param name="state"></param> public void SetVisibility(SprTagVisibility state) { if (!Application.IsConnected) { throw SprExceptions.SprNotConnected; } Application.Windows.TextWindow.Clear(); Application.Activate(); // Get the menu alias character from the enumerator var alias = Char.ConvertFromUtf32((int)state); // Set the tag visibility SendKeys.SendWait(string.Format("%GS{0}", alias)); }
public void OpenAlfrescoPane(bool Show) { if (m_AlfrescoPane == null) { m_AlfrescoPane = new AlfrescoPane(); m_AlfrescoPane.DefaultTemplate = m_DefaultTemplate; m_AlfrescoPane.WordApplication = Application; } if (Show) { m_AlfrescoPane.Show(); if (Application.Documents.Count > 0) { m_AlfrescoPane.showDocumentDetails(); } else { m_AlfrescoPane.showHome(false); } Application.Activate(); } }
protected Application OpenMsWordDocument(string inputFile) { object falseValue = false; object trueValue = true; object missing = Type.Missing; CloseWord(); _word = new Microsoft.Office.Interop.Word.Application(); _word.Visible = true; _word.Activate(); if (!string.IsNullOrEmpty(inputFile)) { object fileName = inputFile; _document = _word.Documents.Open(ref fileName, ref missing, ref falseValue, 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); _document.Activate(); } return(_word); }
public void OpenAlfrescoPane(bool Show) { if (m_AlfrescoPane == null) { m_AlfrescoPane = new AlfrescoPane(); m_AlfrescoPane.DefaultTemplate = m_DefaultTemplate; m_AlfrescoPane.PowerPointApplication = Application; } if (Show) { m_AlfrescoPane.Show(); if (Application.Presentations.Count > 0) { m_AlfrescoPane.showDocumentDetails(); } else { m_AlfrescoPane.showHome(false); } Application.Activate(); m_AppWatcher.AlfrescoWindow = m_AlfrescoPane.Handle.ToInt32(); } }
public void TestActivate() { _application.Activate(); Assert.IsTrue(_application.Active); }
static void Main() { Console.Title = "PowerPad"; // Add global exception handler to log all exceptions AppDomain.CurrentDomain.UnhandledException += handleUnhandledException; // Start server using (var server = new PadServer(Settings.PortNumber)) { printHelp(); if (server.Start()) { // Report which addresses server is listening on Log.Success("Server now listening on:"); foreach (var addr in server.ListeningAddresses) { Log.Success("\t" + addr); } // Wire up PowerPoint events ppt.PresentationOpen += ppt_PresentationOpen; ppt.SlideShowBegin += ppt_SlideShowBegin; ppt.SlideShowEnd += ppt_SlideShowEnd; ppt.SlideShowNextSlide += ppt_SlideShowNextSlide; // Either hook into running instance or start a new instance of PowerPoint up if (ppt.Visible == MsoTriState.msoTrue) { Log.Line("Connected to running PowerPoint instance"); // If there are any opened presentations, notify the user if (ppt.Presentations.Count == 0) { Log.Line("\tNo open presentations"); } else { foreach (Presentation preso in ppt.Presentations) { Log.Line("\t" + formatPresentationNameForConsole(preso)); } } // Do we need to connect to a running slide show? if (ppt.SlideShowWindows.Count > 0) { ppt_SlideShowBegin(ppt.SlideShowWindows[1]); // Has slide show been closed while we were starting it up? if (ActiveSlideShow != null) { ppt_SlideShowNextSlide(ppt.SlideShowWindows[1]); } } } else { Log.Line("Starting up new PowerPoint instance"); ppt.Activate(); } } // Wait for user command var quitting = false; while (!quitting) { var cmd = Console.ReadLine(); switch (cmd) { case "quit": quitting = true; continue; default: Log.Warning("Unknown command: " + cmd); break; } } } }
static int Main() { WordAppMain myWord = new WordAppMain(); int return_Result = 0; // Create a word object that we can manipulate Application Word_App = null; Document Word_doc = null; try { Word_App = new Application(); Word_doc = new Document(); } catch (Exception e) { Console.WriteLine("Can't create a word document " + e.ToString()); return_Result = 1; goto Exit; } AutoCorrect autocorrect = Word_App.AutoCorrect; AutoCorrectEntries autoEntries = autocorrect.Entries; string theEnd = "\nThe End"; autoEntries.Add("Inntroduction", "Introduction"); Documents Docs = Word_App.Documents; if (Docs == null) { Console.WriteLine("Docs is null"); } else { Console.WriteLine("Docs exists:" + Docs.Count); } Word_App.Visible = true; _Document my_Doc = (_Document)Word_doc; Word_doc = Docs.Add(ref missing, ref missing, ref missing, ref missing); object start = 0; object end = 0; Range range = Word_doc.Range(ref missing, ref missing); // add text to the doc -- this contains some deliberate misspellings so that we can correct them in a short while range.Text = "Microsoft Word Interoperability Sample\n\nInntroduction:\n\nMicrosoft .NET will allow the creation of truly distributed XML Web services. These services will integrate and collaborate with a range of complementary services to work for customers in ways that today's internet companies can only dream of. Microsoft .NET will drive the Next Generation Internet and will shift the focus from individual Web sites or devices connected to the Internet, to constellations of computers, devices, and services that work together to deliver broader, richer solutions.\nFor more info go to:\n "; // Wait so the starting state can be admired Thread.Sleep(2000); // Format the title Font fc = new Font(); try { Console.WriteLine("Formatting the title"); start = 0; end = 40; range = Word_doc.Range(ref start, ref end); range.Font.Size = 24; range.Font.Bold = 1; range.Font.Color = WdColor.wdColorGray30; start = 40; end = 54; range = Word_doc.Range(ref start, ref end); range.Font.Size = 14; } catch (Exception e) { Console.WriteLine(" Font exception:{0}", e.ToString()); } // Wait so the new formatting can be appreciated Thread.Sleep(3000); autocorrect.ReplaceTextFromSpellingChecker = true; // Fix inntroduction string obj = "Introduction"; AutoCorrectEntry errEntry = autoEntries.Add("Inntroduction", obj); Words myWords = Word_doc.Words; Range errRange = myWords[7]; errEntry.Apply(errRange); // Add a caption to the window and get it back Window myWindow = Word_App.ActiveWindow; myWindow.Caption = "Managed Word execution from C# "; string gotCaption = myWindow.Caption; if (gotCaption.Equals("Managed Word execution from C# ")) { Console.WriteLine("Caption assigned and got back"); return_Result = 1; } Thread.Sleep(2000); // define the selection object, find and replace text Selection mySelection = myWindow.Selection; try { start = 65; end = 69; range = Word_doc.Range(ref start, ref end); Console.WriteLine("The color of .NET is being changed"); range.Font.Bold = 16; range.Font.Color = WdColor.wdColorLavender; } catch (Exception e) { Console.WriteLine(" Font exception:{0}", e.ToString()); } Thread.Sleep(2000); // underline the selected text range = Word_doc.Range(ref start, ref end); range.Underline = (WdUnderline.wdUnderlineDouble); // add hyperlink and follow the hyperlink Hyperlinks my_Hyperlinks = Word_doc.Hyperlinks; // Make the range past the end of all document text mySelection.Start = 9999; mySelection.End = 9999; range = mySelection.Range; // Add a hyperlink string myAddress = "http://go.microsoft.com/fwlink/?linkid=3269&clcid=0x409"; object obj_Address = myAddress; Console.WriteLine("Adding hyperlink to the document"); Hyperlink my_Hyperlink1 = my_Hyperlinks._Add(range, ref obj_Address, ref missing); Word_App.ActiveWindow.Selection.InsertAfter("\n"); Thread.Sleep(5000); // Open a window to Hyperlink Process ie = Process.Start("iexplore.exe", my_Hyperlink1.Address); // Wait for a short spell to allow the page to be examined Thread.Sleep(10000); // close the browser first Console.WriteLine("Removing browser window"); ie.Kill(); // Display "The End" Word_App.ActiveWindow.Selection.InsertAfter(theEnd); Word_App.ActiveWindow.Selection.Start = 0; Word_App.ActiveWindow.Selection.End = 0; Word_App.Activate(); Thread.Sleep(5000); // Close Microsoft Word object myBool = WdSaveOptions.wdDoNotSaveChanges; Word_App.ActiveWindow.Close(ref myBool, ref missing); Exit: return(return_Result); }
//- #endregion #region Public Methods //---------------------- /// <summary> /// Starts the <see cref="DataControl">DataControl.</see> /// </summary> /// <remarks> /// After starting the <B>DataControl</B> the client will be notified about the <see cref="ValueQT">value</see> changes for all the /// <see cref="ControlDaItem">items</see> selected in the configuration phase. If an item is bound to a /// Windows Forms Control then the new values will be displayed in this one. /// </remarks> /// <include /// file='TBNC.doc.xml' /// path='//class[@name="DataControl"]/method[@name="Start"]/doc/*' /// /> public void Start() { try { if (m_session == null) { return; } this.Clear(); if (this.BinaryLicenseDa != string.Empty) { m_instance.Activate(EnumFeature.DA_CLIENT, this.BinaryLicenseDa); } if (this.BinaryLicenseXmlDa != string.Empty) { m_instance.Activate(EnumFeature.DA_CLIENT, this.BinaryLicenseXmlDa); } m_instance.Initialize(); m_newSession = new ControlDaSession(m_session.StoredUrl); m_newSession.Connect(false, true, new ExecutionOptions()); m_newSession.ShutdownRequest += new ShutdownEventHandler(HandleSessionShutdownWithReconnection); if (m_session.SubscriptionList.Length == 0) { return; } foreach (ControlDaSubscription currentSubscription in m_session.SubscriptionList) { ControlDaSubscription controlSubscription = new ControlDaSubscription( currentSubscription.StoredUpdateRate, m_newSession); if (controlSubscription.Valid) { controlSubscription.Name = currentSubscription.StoredName; controlSubscription.StoredName = controlSubscription.Name; controlSubscription.StoredUpdateRate = controlSubscription.RequestedUpdateRate; controlSubscription.IsActivated = currentSubscription.IsActivated; controlSubscription.DataChanged += new DataChangedEventHandler(ControlSubscription_DataChange); DaItem[] items = currentSubscription.ItemList; for (int i = 0; i < items.Length; i++) { ControlDaItem controlItem = new ControlDaItem( ((ControlDaItem)items[i]).StoredId, controlSubscription); this.Add(controlItem); } // end for if (controlSubscription.IsActivated) { controlSubscription.Connect(true, true, new ExecutionOptions()); } // end if } // end if } // end foreach m_session.Handle = m_newSession.Handle; } catch (Exception exc) { m_instance.Trace( EnumTraceLevel.ERR, EnumTraceGroup.CLIENT, "DataControl.Start", exc.ToString()); } } // end Start
public async Task LaunchAsync(CancellationTokenSource cancellationTokenSource = null) { string fileName = Path.GetFileName(this._FileName); if (_Logger.IsTraceEnabled) { _Logger.Trace("Launching {0}", fileName); } if (this.IsWaitingForFinish) { if (_Logger.IsWarnEnabled) { _Logger.Warn("The document {0} is already launched", fileName); } } this._CurrentApp = null; this._CurrentDocument = null; this._isCloseRequested = false; try { if (this.Opening != null) { this.Opening(this, EventArgs.Empty); } using (var app = new Application { Visible = true, DisplayAlerts = WdAlertLevel.wdAlertsNone, DisplayRecentFiles = false, Caption = Resources.PendarEditorTitle }) { try { app.Console.Mode = DebugConsoleMode.Trace; app.Console.AppendTimeInfoEnabled = true; app.DocumentBeforeCloseEvent += this.App_DocumentBeforeCloseEvent; app.DocumentBeforeSaveEvent += this.App_DocumentBeforeSaveEvent; app.DocumentBeforePrintEvent += this.App_DocumentBeforePrintEvent; app.DocumentChangeEvent += this.App_DocumentChangeEvent; app.DocumentOpenEvent += this.App_DocumentOpenEvent; app.NewDocumentEvent += this.App_NewDocumentEvent; app.QuitEvent += this.App_QuitEvent; app.StartupEvent += this.App_StartupEvent; app.Options.AllowReadingMode = false; this._CurrentApp = app; this._isQuit = false; this._isFinished = false; this.IsWaitingForFinish = false; this.IsSaved = false; //try //{ // app.Activate(); //} //catch (Exception exp) //{ // if (_Logger.IsWarnEnabled) // _Logger.Warn(exp, "Error while activating the Word application"); //} try { app.KeyboardBidi(); } catch (COMException exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error while setting the BIDI keyboard"); } } if (_Logger.IsDebugEnabled) { _Logger.Debug("The Word application initialized"); } using (var doc = app.Documents.Open(this._FileName, true, false, false)) { this._CurrentDocument = doc; try { doc.Settings.EnableAutomaticQuit = true; doc.Settings.EnableMoreDebugOutput = Internal.IsDebug; doc.Settings.EnableEventDebugOutput = Internal.IsDebug; doc.Settings.EnableEvents = true; doc.Settings.ExceptionMessageBehavior = ExceptionMessageHandling.CopyInnerExceptionMessageToTopLevelException; doc.Settings.EnableSafeMode = Internal.IsDebug; if (_Logger.IsDebugEnabled) { _Logger.Debug("Word document initialized"); } if (!this.CanChange) { if (_Logger.IsInfoEnabled) { _Logger.Info("Read-Only Word document. Protecting..."); } try { doc.Final = true; } catch (COMException exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error while finalizing the Word document. Maybe the Word is not activated."); } } try { doc.Protect(WdProtectionType.wdAllowOnlyFormFields, true, password: Guid.NewGuid().ToString("N")); } catch (COMException exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error while protecting the Word document. Maybe the Word is not activated."); } } try { doc.Saved = true; } catch (COMException exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error while setting document as saved"); } } } } finally { if (_Logger.IsTraceEnabled) { _Logger.Trace("Activating the Word window."); } //await TaskEx.Delay(50); // not available in C# 5.0 app.Activate(); //doc.Activate(); if (_Logger.IsTraceEnabled) { _Logger.Trace("The Word application activated"); } } //if (this.CanChange) { this.IsWaitingForFinish = true; if (_Logger.IsDebugEnabled) { _Logger.Debug("Waiting for the Word document to close"); } await this.WaitForExitAsync(() => this._MessageInfo.CloseRequested, cancellationTokenSource); if (this._isCloseRequested || cancellationTokenSource.IsCancellationRequested) { _Logger.Warn("Saving Word document canceled"); this.IsSaved = false; } if (_Logger.IsInfoEnabled) { _Logger.Info("The Word document is closed"); } this.IsWaitingForFinish = false; } //else //{ // try // { // app.DisplayAlerts = WdAlertLevel.wdAlertsNone; // } // catch (Exception exp) // { // if (_Logger.IsWarnEnabled) // _Logger.Warn(exp, "Error preventing alerts to display"); // } // this.IsSaved = false; //} } } finally { if (!this._isQuit && this.CanChange) { try { if (_Logger.IsDebugEnabled) { _Logger.Debug("Quiting the Word application"); } app.Quit(false, true); if (_Logger.IsDebugEnabled) { _Logger.Debug("Quited the Word application"); } } catch (COMException exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error while quiting the Word application"); } } } } } } finally { this._CurrentDocument = null; this._CurrentApp = null; } if (this.Finished != null) { this.Finished(this, EventArgs.Empty); } if (_Logger.IsInfoEnabled) { _Logger.Info("Launching Word finished"); } }
public async Task PrintAsync(bool withPreview, CancellationTokenSource cancellationTokenSource = null) { string fileName = Path.GetFileName(this._FileName); if (_Logger.IsTraceEnabled) { _Logger.Trace("Launching {0}", fileName); } this._CurrentApp = null; this._CurrentDocument = null; using (var app = new Application { Visible = true, DisplayAlerts = WdAlertLevel.wdAlertsNone, DisplayRecentFiles = false, Caption = Resources.PendarEditorTitle }) { try { app.Console.Mode = DebugConsoleMode.Trace; app.Console.AppendTimeInfoEnabled = true; app.DisplayAlerts = WdAlertLevel.wdAlertsNone; app.DocumentBeforeCloseEvent += this.App_DocumentBeforeCloseEvent; app.DocumentBeforeSaveEvent += this.App_DocumentBeforeSaveEvent; app.DocumentBeforePrintEvent += this.App_DocumentBeforePrintEvent; app.DocumentChangeEvent += this.App_DocumentChangeEvent; app.DocumentOpenEvent += this.App_DocumentOpenEvent; app.NewDocumentEvent += this.App_NewDocumentEvent; app.QuitEvent += this.App_QuitEvent; app.StartupEvent += this.App_StartupEvent; app.Options.AllowReadingMode = true; this._CurrentApp = app; this._isQuit = false; this._isFinished = false; this.IsSaved = false; this.IsWaitingForFinish = false; try { app.Options.ArabicNumeral = WdArabicNumeral.wdNumeralContext; app.Options.BackgroundSave = false; app.Options.CreateBackup = false; app.Options.DocumentViewDirection = WdDocumentViewDirection.wdDocumentViewRtl; app.Options.MeasurementUnit = WdMeasurementUnits.wdMillimeters; app.Options.MonthNames = WdMonthNames.wdMonthNamesFrench; app.Options.DefaultTextEncoding = NetOffice.OfficeApi.Enums.MsoEncoding.msoEncodingUTF8; app.Options.ShowDevTools = false; } catch (COMException exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error while setting the Word options"); } } using (var doc = app.Documents.Open(this._FileName, true, false, false)) { doc.Settings.EnableAutomaticQuit = true; doc.Settings.EnableMoreDebugOutput = Internal.IsDebug; doc.Settings.EnableEventDebugOutput = Internal.IsDebug; doc.Settings.EnableEvents = true; doc.Settings.ExceptionMessageBehavior = ExceptionMessageHandling.CopyInnerExceptionMessageToTopLevelException; doc.Settings.EnableSafeMode = Internal.IsDebug; try { doc.Protect(WdProtectionType.wdAllowOnlyFormFields, true, password: Guid.NewGuid().ToString("N")); } catch (COMException exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error while protecting the document"); } } try { doc.ReadOnlyRecommended = true; } catch (COMException exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error in the ReadOnlyRecommended"); } } try { doc.Saved = true; } catch (COMException exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error while setting document as saved"); } } try { if (withPreview) { doc.PrintPreview(); app.Activate(); await this.WaitForExitAsync(cancellationTokenSource : cancellationTokenSource); } else { doc.PrintOut(); } await TaskEx.Delay(90); } finally { try { doc.ClosePrintPreview(); } catch (Exception exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error while closing the print preview"); } } try { doc.Close(false); } catch (Exception exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error while closing the word document"); } } } } } finally { try { if (_Logger.IsDebugEnabled) { _Logger.Debug("Quiting the word application"); } if (!this._isQuit) { app.Quit(false, true); } if (_Logger.IsDebugEnabled) { _Logger.Debug("Quited the word application"); } } catch (COMException exp) { if (_Logger.IsWarnEnabled) { _Logger.Warn(exp, "Error while quiting the word Application"); } } } } }
public DataSet ImportTablesToDataSet() { Application appPPT = new Application(); appPPT.Visible = Microsoft.Office.Core.MsoTriState.msoFalse; appPPT.Activate(); Presentation apPresentation = appPPT.Presentations.Open2007(FilePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse); int intTables = 0; foreach (Slide pSlide in apPresentation.Slides) { foreach (Shape pShape in pSlide.Shapes) { if (pShape.HasTable.Equals(Microsoft.Office.Core.MsoTriState.msoTrue)) { intTables++; Table dt = pShape.Table; int intRowsCounter = 1 + RowsToSkip; System.Data.DataTable m_DataTable = new System.Data.DataTable("DT_" + intTables); int intColumnsCounter = 0; if (intRowsCounter > dt.Rows.Count) { return(null); } if (HasHeader) { for (int i = 1; i == dt.Columns.Count; i++) { m_DataTable.Columns.Add(dt.Cell(intRowsCounter, i).Shape.TextFrame.HasText.Equals(Microsoft.Office.Core.MsoTriState.msoTrue) ? dt.Cell(intRowsCounter, i).Shape.TextFrame.TextRange.Text.Trim() : "F" + i.ToString()); } intRowsCounter++; } else { for (int i = 1; i == dt.Columns.Count; i++) { m_DataTable.Columns.Add("F" + i.ToString()); } } while (intRowsCounter <= dt.Rows.Count) { DataRow drRow = m_DataTable.NewRow(); for (intColumnsCounter = 1; intColumnsCounter == dt.Columns.Count; intColumnsCounter++) { drRow[intColumnsCounter - 1] = dt.Cell(intRowsCounter, intColumnsCounter).Shape.TextFrame.HasText.Equals(Microsoft.Office.Core.MsoTriState.msoTrue) ? dt.Cell(intRowsCounter, intColumnsCounter).Shape.TextFrame.TextRange.Text.Trim() : ""; } m_DataTable.Rows.Add(drRow); intRowsCounter++; } Maindataset.Tables.Add(m_DataTable); } } } apPresentation.Close(); appPPT.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(apPresentation); System.Runtime.InteropServices.Marshal.ReleaseComObject(appPPT); return(Maindataset); }
public void Activate() { Application.Activate(); }