private void Document_ContextMenuShowing(object sender, HtmlElementEventArgs e) { IHTMLDocument2 htmlDocument = currentBrowser.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection.type == "Text") { IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range != null || range.text.Trim() != "") { currentBrowser.ContextMenuStrip = cmsText; if (range.text.Length <= 30) { searchTSMI.Text = string.Format("Search \"{0}\" in the Web", range.text); } else { searchTSMI.Text = string.Format("Search \"{0}\" in the Web", range.text.Substring(0, 30)); } WordToSearch = range.text; } } else { currentBrowser.ContextMenuStrip = cmsGeneral; } }
private string GetHtmlDocSelectedText(mshtml.IHTMLDocument2 htmlDoc, bool html) { IHTMLSelectionObject selobj = null; IHTMLTxtRange range = null; if ((htmlDoc == null) || (htmlDoc.selection == null)) { return(string.Empty); } selobj = htmlDoc.selection as IHTMLSelectionObject; if (selobj == null) { return(string.Empty); } range = selobj.createRange() as IHTMLTxtRange; if (range == null) { return(string.Empty); } if (html) { return(range.htmlText); } else { return(range.text); } }
/// <summary> /// 1) If nothing is selected returns false /// 2) If the user has selected text or multiple elements /// inserts s_BeginHtml before and s_EndHtml behind the current selection /// 3)If the user has selected a control returns false /// </summary> /// <param name="s_BeginHtml"></param> /// <param name="s_EndHtml"></param> /// <returns></returns> // Example s_BeginHtml = "<SUB>", s_EndHtml = "</SUB>" will subscript the selected text // Example s_BeginHtml = "", s_EndHtml = "<BR>" will add a BR to the end of the selected text //AddToSelection(string.Empty, "<br>"); public bool AddToSelection(string s_BeginHtml, string s_EndHtml) { if (m_pDoc2 == null) { return(false); } IHTMLSelectionObject sel = m_pDoc2.selection as IHTMLSelectionObject; if (sel == null) { return(false); } IHTMLTxtRange range = sel.createRange() as IHTMLTxtRange; if (range == null) { return(false); } string shtml = string.Empty; if (!string.IsNullOrEmpty(s_BeginHtml)) { shtml = s_BeginHtml + range.htmlText; } if (!string.IsNullOrEmpty(s_EndHtml)) { shtml += s_EndHtml; } range.pasteHTML(shtml); range.collapse(false); range.select(); return(true); }
private void toolStripButton5_Click(object sender, EventArgs e) { //string URL = "http://www.example.com"; //string Text = "Example.com"; string s = ""; IHTMLSelectionObject currentSelection = doc.selection; if (currentSelection != null) { IHTMLTxtRange r = currentSelection.createRange() as IHTMLTxtRange; if (r != null) { s = r.text; } } IHTMLTxtRange range = doc.selection.createRange() as IHTMLTxtRange; FormLink frm = new FormLink(); frm.tbxTexto.Text = s; frm.ShowDialog(); range.pasteHTML("<A href=\"" + frm.URL + "\">" + frm.Texto + "</A>"); range.collapse(false); range.select(); }
public bool AddToSelection(IHTMLDocument2 m_pDoc2, string s_BeginHtml, string s_EndHtml) { if (m_pDoc2 == null) { return(false); } IHTMLSelectionObject sel = m_pDoc2.selection as IHTMLSelectionObject; IHTMLElement ele = m_pDoc2.activeElement as IHTMLElement; if (sel == null) { return(false); } IHTMLTxtRange range = sel.createRange() as IHTMLTxtRange; if (range == null) { return(false); } string shtml = string.Empty; if (!string.IsNullOrEmpty(s_BeginHtml)) { shtml = s_BeginHtml + range.htmlText + s_EndHtml; } range.pasteHTML(shtml); range.select(); return(true); }
/// <summary> /// The currently selected text/controls will be replaced by the given HTML code. /// If nothing is selected, the HTML code is inserted at the cursor position /// </summary> /// <param name="s_Html"></param> /// <returns></returns> public bool PasteIntoSelection(string s_Html) { if (m_pDoc2 == null) { return(false); } IHTMLSelectionObject sel = m_pDoc2.selection as IHTMLSelectionObject; if (sel == null) { return(false); } IHTMLTxtRange range = sel.createRange() as IHTMLTxtRange; if (range == null) { return(false); } //none //text //control if ((!String.IsNullOrEmpty(sel.EventType)) && (sel.EventType == "control")) { IHTMLControlRange ctlrange = range as IHTMLControlRange; if (ctlrange != null) //Control(s) selected { IHTMLElement elem = null; int ctls = ctlrange.length; for (int i = 0; i < ctls; i++) { //Remove all selected controls elem = ctlrange.item(i); if (elem != null) { RemoveNode(elem, true); } } // Now get the textrange after deleting all selected controls range = null; range = sel.createRange() as IHTMLTxtRange; } } if (range != null) { // range will be valid if nothing is selected or if text is selected // or if multiple elements are seleted range.pasteHTML(s_Html); range.collapse(false); range.select(); } return(true); }
//=======================================================BOTONES======================================================= //Copia el texto seleccionado para leerlo private void BtnCopy_Click(object sender, EventArgs e) { IHTMLDocument2 htmldoc = webBrowser1.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmldoc.selection; if (currentSelection != null) { if (currentSelection.createRange() is IHTMLTxtRange range) { txtConvertedText.Text = range.text; } } }
private void chercherDansLaPageToolStripMenuItem_Click(object sender, EventArgs e) { IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection != null) { IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range != null && dataGridView3.RowCount > 0) { string keywords = range.text; //DataView dv = (DataView)dataGridView3.DataSource; var dv = new DataView(dt_annonces); StringBuilder sb = new StringBuilder(); if (keywords != null) { for (int i = 0; i < keywords.Length; i++) { char c = keywords[i]; if (c == '*' || c == '%' || c == '[' || c == ']') { sb.Append("[").Append(c).Append("]"); } else if (c == '\'') { sb.Append("''"); } else { sb.Append(c); } } } string rule = @"source like '%keywords%'".Replace("keywords", sb.ToString()); dv.RowFilter = rule; dataGridView3.DataSource = dv; /* * foreach(DataRow dr in dataGridView3.Rows) * { * dr["source"].ToString().Contains(keywords); * * } */ } } }
void CopyScreen() { IHTMLDocument2 htmldoc = webBrowser1.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject selection = htmldoc.selection; IHTMLTxtRange range = selection.createRange() as IHTMLTxtRange; if (selection != null) { if (range != null) { convert = range.text; } } }
private void btnCopyScreen_Click(object sender, EventArgs e) { IHTMLDocument2 htmlDocument = webSearchShow.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmlDocument.selection; IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (currentSelection != null) { if (range != null) { text.Text = range.text; } } }
public string GetSelected(bool html = false) { IHTMLDocument2 htmlDocument = Browser.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection != null) { IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range != null) { return(html ? range.htmlText : range.text); } } return(""); }
private void CopyScreenBtn_Click(object sender, EventArgs e) { IHTMLDocument2 hTMLDocument = webbrowser1.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = hTMLDocument.selection; IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (currentSelection != null) { if (range != null) { converttxt.Text = range.text; } } }
/// <summary> /// Returns whether there is currently any text selected /// Only works if Microsoft.mshtml.dll is available /// </summary> /// <returns></returns> private bool TextSelectedChecked() { IHTMLDocument2 htmlDocument = Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection= htmlDocument.selection; if (currentSelection!=null) { IHTMLTxtRange range= currentSelection.createRange() as IHTMLTxtRange; if (range != null && !string.IsNullOrEmpty(range.text)) return true; } return false; }
protected void Button4_Click(object sender, EventArgs e) { IHTMLDocument2 htmlDocument = (IHTMLDocument2)this.form1.InnerHtml; IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection != null) { IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range != null) { MessageBox.Show(range.text); } } }
private void ReadBtn_Click(object sender, EventArgs e) { IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmlDocument.selection; IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (currentSelection != null) { if (range != null) { ConvertedText.Text = range.text; } } ReadBtn.Enabled = false; PauseBtn.Enabled = true; s.SpeakAsync(ConvertedText.Text); }
private void btnTranslate_Click(object sender, EventArgs e) { string textToTranslate = ""; IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection != null) { IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range != null) { textToTranslate = range.text; } } try { if (String.IsNullOrEmpty(textToTranslate)) { textToTranslate = getInput(textToTranslate, htmlDocument); } System.Diagnostics.Process.Start(String.Format("https://translate.google.pl/#view=home&op=translate&sl=en&tl=pl&text={0}", replace(textToTranslate))); } catch (WebException exc) { MessageBox.Show("Brak połączenia z internetem lub antywirus blokuje połączenie, próba w otwarcia przeglądarce. \n" + exc.Message, "Błąd!"); try { if (String.IsNullOrEmpty(textToTranslate)) { textToTranslate = htmlDocument.body.innerText; } System.Diagnostics.Process.Start(String.Format("https://translate.google.pl/#view=home&op=translate&sl=en&tl=pl&text={0}", replace(textToTranslate))); } catch (WebException) { MessageBox.Show("Brak połączenia z internetem? Brak połączenia z ...www.google.com/translate...", "Błąd!"); return; } return; } catch (Exception exc) { MessageBox.Show("Problem z tłumaczeniem.", "Nieznany błąd!"); return; } }
private void CopyScreen_Click(object sender, EventArgs e) { /////////////////copy screen //////////////////////////////// IHTMLDocument2 htmlDocument = webreaderbrow.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmlDocument.selection; IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (currentSelection != null) { if (range != null) { convertedtxt.Text = range.text; //btnPlay.PerformClick(); } } //////////////end here ///////////////////////////////////// }
private string SelectedText() { IHTMLDocument2 htmlDocument = Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection != null) { IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range != null && !string.IsNullOrEmpty(range.text)) { return(range.text); } } return(""); }
/// <summary> /// Returns whether there is currently any text selected /// </summary> /// <returns></returns> public bool TextSelected() { IHTMLDocument2 htmlDocument = Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection != null) { IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range != null && !string.IsNullOrEmpty(range.text)) { return(true); } } return(false); }
public void addControl(string html) { cEXWB1.Focus(); IHTMLDocument2 doc2 = null; IHTMLSelectionObject selobj = null; IHTMLTxtRange range = null; doc2 = cEXWB1.GetActiveDocument(); if ((doc2 == null) || (doc2.selection == null)) { return; } selobj = doc2.selection as IHTMLSelectionObject; if (selobj == null) { return; } if ((selobj.EventType == "none") || (selobj.EventType == "control")) { return; } try { range = selobj.createRange() as IHTMLTxtRange; if (range == null) { return; } range.pasteHTML(html); } catch (Exception exp) { } return; }
private string TextRange() { if (Document == null) { return(null); } if (!(Document.DomDocument is IHTMLDocument2 htmlDocument)) { return(null); } IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection == null || !(currentSelection.createRange() is IHTMLTxtRange range)) { return(null); } return(range.text); }
public static bool SelectionIsImage(IHTMLSelectionObject selection) { // see if we have selected an image if (selection != null && selection.type == "Control") { object range = selection.createRange(); if (range is IHTMLControlRange) { IHTMLControlRange controlRange = (IHTMLControlRange)range; if (controlRange.length > 0) { IHTMLElement selectedElement = controlRange.item(0); if (selectedElement is IHTMLImgElement) return true; } } } // got this far, not an image! return false; }
private void tsmiMove_Click(object sender, EventArgs e) { IHTMLDocument2 htmlDocument = this.webBrowserSVG.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmlDocument.selection; //var x = webBrowserSVG.Document.GetElementById("idText123"); //x.setAttributeNS(null, "x" ,200); //MessageBox.Show(x.Parent.Id); if (currentSelection != null) { MessageBox.Show(currentSelection.type); //IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; //if (range != null) //{ // MessageBox.Show(range.text); //} } }
private void btnSpeak_Click(object sender, EventArgs e) { string input = ""; IHTMLDocument2 htmlDocument = webBrowser1.Document.DomDocument as IHTMLDocument2; IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection != null) { IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range != null) { input = range.text; } } try { input = getInput(input, htmlDocument); Talk talk = new Talk(input, getQuestionNumber()); } catch { } }
/// <summary> /// Create a MarkupRange from a selection object. /// </summary> public MarkupRange CreateMarkupRange(IHTMLSelectionObject selection) { if (selection == null) { return(null); } // see what type of range is selected object range = selection.createRange(); if (range is IHTMLTxtRange) { return(CreateMarkupRange(range as IHTMLTxtRange)); } else if (range is IHTMLControlRange) { // we only support single-selection so a "control-range" can always // be converted into a single-element text range IHTMLControlRange controlRange = range as IHTMLControlRange; if (controlRange.length == 1) { IHTMLElement selectedElement = controlRange.item(0); MarkupRange markupRange = CreateMarkupRange(selectedElement); //return the precisely positioned text range return(markupRange); } else { Debug.Fail("Length of control range not equal to 1 (value was " + controlRange.length.ToString(CultureInfo.InvariantCulture)); return(null); } } else // null or unexpected range type { return(null); } }
public static bool SelectionIsImage(IHTMLSelectionObject selection) { // see if we have selected an image if (selection != null && selection.type == "Control") { object range = selection.createRange(); if (range is IHTMLControlRange) { IHTMLControlRange controlRange = (IHTMLControlRange)range; if (controlRange.length > 0) { IHTMLElement selectedElement = controlRange.item(0); if (selectedElement is IHTMLImgElement) { return(true); } } } } // got this far, not an image! return(false); }
private void ProcessPasteFromWebBrowser() { if (_beginSelection) { _beginSelection = false; var activeControl = FormManager.LastActiveControl as TextBox; if (activeControl != null && webBrowser.Document != null) { var htmlDocument = webBrowser.Document.DomDocument as IHTMLDocument2; if (htmlDocument != null) { IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection != null) { var range = currentSelection.createRange() as IHTMLTxtRange; if (range != null) { activeControl.SelectedText = range.text; } } } } } }
void ExtractLinks(bool bOnlySelected) { using (new WaitCursor()) { DateTime start = DateTime.Now; while (wbBase.ReadyState < WebBrowserReadyState.Interactive) { Application.DoEvents(); TimeSpan ts = DateTime.Now.Subtract(start); if (ts.Seconds > 10) { switch (CppUtils.CenteredMessageBox(this, Properties.Resources.CancelCompleteCheck, Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)) { case DialogResult.No: start = DateTime.Now; continue; case DialogResult.Cancel: return; } break; } } if (bOnlySelected) { try { IHTMLDocument2 htmlDocument = wbBase.Document.DomDocument as IHTMLDocument2; if (htmlDocument == null) { throw new Exception("No htmlDocument"); } IHTMLSelectionObject currentSelection = htmlDocument.selection; if (currentSelection == null) { throw new Exception("No Selection"); } //if (currentSelection.type == "Text") // throw new Exception("No Links in the selection"); //if(currentSelection.type!="Control") // throw new Exception("No Links in the selection"); IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range == null) { throw new Exception("No Links in the selection"); } string html = range.htmlText; if (string.IsNullOrEmpty(html)) { throw new Exception("No Links in the selection"); } string[] urls = GetUrlsFromHtml(html, wbBase.Url.AbsoluteUri); foreach (string url in urls) { addToListIfNotEmpty(url); } } catch (Exception ex) { CppUtils.CenteredMessageBox(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { HtmlDocument doc = wbBase.Document; Dictionary <string, int> tagcounter = new Dictionary <string, int>(); // List<string> urls = new List<string>(); foreach (HtmlElement elm in doc.All) { if (elm.TagName == "a" || elm.TagName == "A") { string url = elm.GetAttribute("href"); // urls.Add(url); // listUrls.Items.Add(url); addToListIfNotEmpty(url); } } } } }
private static bool ExportToInspector(Inspector inspector, string tmpFile, string subject) { Item currentMail = inspector.CurrentItem; if (currentMail == null) { LOG.Debug("No current item."); return(false); } if (!OlObjectClass.olMail.Equals(currentMail.Class)) { LOG.Debug("Item is no mail."); return(false); } try { if (currentMail.Sent) { LOG.Debug("Item already sent"); return(false); } // Make sure the inspector is activated, only this way the word editor is active! // This also ensures that the window is visible! inspector.Activate(); // Check for wordmail, if so use the wordexporter if (inspector.IsWordMail() && inspector.WordEditor != null) { if (WordExporter.InsertIntoExistingDocument(inspector.WordEditor, tmpFile)) { LOG.Debug("Inserted into Wordmail"); return(true); } } else { LOG.Debug("Wordmail editor is not supported"); } LOG.DebugFormat("Email '{0}' has format: {1}", currentMail.Subject, currentMail.BodyFormat); string contentID; if (outlookVersion.Major >= 12) { contentID = Guid.NewGuid().ToString(); } else { LOG.Info("Older Outlook (<2007) found, using filename as contentid."); contentID = Path.GetFileName(tmpFile); } bool inlinePossible = false; if (OlBodyFormat.olFormatHTML.Equals(currentMail.BodyFormat)) { // if html we can try to inline it // The following might cause a security popup... can't ignore it. try { IHTMLDocument2 document2 = inspector.HTMLEditor as IHTMLDocument2; if (document2 != null) { IHTMLSelectionObject selection = document2.selection; if (selection != null) { IHTMLTxtRange range = selection.createRange(); if (range != null) { // First paste, than attach (otherwise the range is wrong!) range.pasteHTML("<BR/><IMG border=0 hspace=0 alt=\"" + subject + "\" align=baseline src=\"cid:" + contentID + "\"><BR/>"); inlinePossible = true; } else { LOG.DebugFormat("No range for '{0}'", inspector.Caption); } } else { LOG.DebugFormat("No selection for '{0}'", inspector.Caption); } } else { LOG.DebugFormat("No HTML editor for '{0}'", inspector.Caption); } } catch (Exception e) { LOG.Warn("Error pasting HTML, most likely due to an ACCESS_DENIED as the user clicked no.", e); // Continue with non inline image } } // Create the attachment (if inlined the attachment isn't visible as attachment!) Attachment attachment = currentMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, inlinePossible?0:1, subject); if (outlookVersion.Major >= 12) { // Add the content id to the attachment try { PropertyAccessor propertyAccessor = attachment.PropertyAccessor; propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID); } catch { } } } catch (Exception ex) { LOG.DebugFormat("Problem while trying to add attachment to MailItem '{0}' : {1}", inspector.Caption, ex); return(false); } LOG.Debug("Finished!"); return(true); }
public static bool AddToSelection(IHTMLDocument2 m_pDoc2, string s_BeginHtml, string s_EndHtml) { if (m_pDoc2 == null) { return(false); } IHTMLSelectionObject sel = m_pDoc2.selection as IHTMLSelectionObject; IHTMLElement ele = m_pDoc2.activeElement as IHTMLElement; if (sel == null) { return(false); } IHTMLTxtRange range = sel.createRange() as IHTMLTxtRange; if (range == null) { return(false); } string shtml = string.Empty; if (!string.IsNullOrEmpty(s_BeginHtml)) { if (s_EndHtml.IndexOf("span") < 0) { shtml = s_BeginHtml + range.htmlText + s_EndHtml; } else { #region string xmstr = GeneralMethods.tidy(range.htmlText); if (xmstr.Length > 4) { xmstr = xmstr.Replace("\n", "");//去掉/n/r } xmstr = xmstr.Replace("\r", ""); string[] style = new string[100]; int i = 0; int span = xmstr.IndexOf("span"); string spanstr = ((span == 1) ? "</span>" : ""); while (xmstr.Length > 0) //将选中字符串分段存入数组 { if (xmstr.IndexOf("<span") != 0) //span处理的字符串不在最前 { if (xmstr.IndexOf("<span") == -1) //没有span的情况,即没有经过样式处理的字符串 { style[i++] = xmstr; xmstr = ""; break; } style[i++] = xmstr.Substring(0, xmstr.IndexOf("<span")); xmstr = xmstr.Substring(xmstr.IndexOf("<span")); } else {//将span处理的字符串存入数组 int spans = xmstr.IndexOf("<span"); int spand = xmstr.IndexOf("</span>"); if (spand != -1 && spans != -1) { style[i++] = xmstr.Substring(spans, spand + 7); xmstr = xmstr.Substring(spand + 7); } } } int k = -1; for (int j = 0; j < style.Length; j++) { if (style[j] != null && style[j] != " ") { if (style[j].IndexOf("span") > -1)//如果包含Span { k++; if (k == 0) { style[j] = "</span>" + style[j].Substring(0, style[j].IndexOf(">") - 1) + ";" + s_BeginHtml + style[j].Substring(style[j].IndexOf(">") - 1); } else { style[j] = style[j].Substring(0, style[j].IndexOf(">") - 1) + ";" + s_BeginHtml + style[j].Substring(style[j].IndexOf(">") - 1); } } else { k++; style[j] = "<span style='" + s_BeginHtml + "'>" + style[j] + "</span>"; } spanstr += style[j]; } if (style[j] == null) { break; } } #endregion if (spanstr.IndexOf("spanstyle") > -1) { spanstr = spanstr.Replace("spanstyle", "span style"); } shtml = spanstr; } } //if (shtml.Contains("CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95")) //{ // shtml=shtml.Replace("CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95", "{id}"); //} range.pasteHTML(shtml); range.findText("cao", 0, 0); //range.collapse(false); range.select(); return(true); }
/// <summary> /// Create a MarkupRange from a selection object. /// </summary> public MarkupRange CreateMarkupRange(IHTMLSelectionObject selection) { if (selection == null) { return null; } // see what type of range is selected object range = selection.createRange(); if (range is IHTMLTxtRange) { return CreateMarkupRange(range as IHTMLTxtRange); } else if (range is IHTMLControlRange) { // we only support single-selection so a "control-range" can always // be converted into a single-element text range IHTMLControlRange controlRange = range as IHTMLControlRange; if (controlRange.length == 1) { IHTMLElement selectedElement = controlRange.item(0); MarkupRange markupRange = CreateMarkupRange(selectedElement); //return the precisely positioned text range return markupRange; } else { Debug.Fail("Length of control range not equal to 1 (value was " + controlRange.length.ToString(CultureInfo.InvariantCulture)); return null; } } else // null or unexpected range type { return null; } }
/// <summary> /// Export the file to the supplied inspector /// </summary> /// <param name="inspector">Inspector</param> /// <param name="currentItem">Item</param> /// <param name="tmpFile"></param> /// <param name="attachmentName"></param> /// <returns></returns> private static bool ExportToInspector(Inspector inspector, Item currentItem, string tmpFile, string attachmentName) { if (currentItem == null) { LOG.Warn("No current item."); return(false); } OlObjectClass itemClass = currentItem.Class; bool isMail = OlObjectClass.olMail.Equals(itemClass); bool isAppointment = OlObjectClass.olAppointment.Equals(itemClass); if (!isMail && !isAppointment) { LOG.Warn("Item is no mail or appointment."); return(false); } MailItem mailItem = null; try { if (isMail) { //mailItem = COMWrapper.Cast<MailItem>(currentItem); mailItem = (MailItem)currentItem; if (mailItem.Sent) { LOG.WarnFormat("Item already sent, can't export to {0}", currentItem.Subject); return(false); } } // Make sure the inspector is activated, only this way the word editor is active! // This also ensures that the window is visible! inspector.Activate(); bool isTextFormat = false; if (isMail) { isTextFormat = OlBodyFormat.olFormatPlain.Equals(mailItem.BodyFormat); } if (isAppointment || !isTextFormat) { // Check for wordmail, if so use the wordexporter // http://msdn.microsoft.com/en-us/library/dd492012%28v=office.12%29.aspx // Earlier versions of Outlook also supported an Inspector.HTMLEditor object property, but since Internet Explorer is no longer the rendering engine for HTML messages and posts, HTMLEditor is no longer supported. if (inspector.IsWordMail() && inspector.WordEditor != null) { try { if (WordExporter.InsertIntoExistingDocument(inspector.WordEditor.Application, inspector.WordEditor, tmpFile, null, null)) { LOG.Info("Inserted into Wordmail"); // check the format afterwards, otherwise we lose the selection //if (!OlBodyFormat.olFormatHTML.Equals(currentMail.BodyFormat)) { // LOG.Info("Changing format to HTML."); // currentMail.BodyFormat = OlBodyFormat.olFormatHTML; //} return(true); } } catch (Exception exportException) { LOG.Error("Error exporting to the word editor, trying to do it via another method", exportException); } } else if (isAppointment) { LOG.Info("Can't export to an appointment if no word editor is used"); return(false); } else { LOG.Info("Trying export for outlook < 2007."); } } // Only use mailitem as it should be filled!! LOG.InfoFormat("Item '{0}' has format: {1}", mailItem.Subject, mailItem.BodyFormat); string contentID; if (outlookVersion.Major >= OUTLOOK_2007) { contentID = Guid.NewGuid().ToString(); } else { LOG.Info("Older Outlook (<2007) found, using filename as contentid."); contentID = Path.GetFileName(tmpFile); } // Use this to change the format, it will probably lose the current selection. //if (!OlBodyFormat.olFormatHTML.Equals(currentMail.BodyFormat)) { // LOG.Info("Changing format to HTML."); // currentMail.BodyFormat = OlBodyFormat.olFormatHTML; //} bool inlinePossible = false; if (OlBodyFormat.olFormatHTML.Equals(mailItem.BodyFormat)) { // if html we can try to inline it // The following might cause a security popup... can't ignore it. try { IHTMLDocument2 document2 = inspector.HTMLEditor as IHTMLDocument2; if (document2 != null) { IHTMLSelectionObject selection = document2.selection; if (selection != null) { IHTMLTxtRange range = selection.createRange(); if (range != null) { // First paste, than attach (otherwise the range is wrong!) range.pasteHTML("<BR/><IMG border=0 hspace=0 alt=\"" + attachmentName + "\" align=baseline src=\"cid:" + contentID + "\"><BR/>"); inlinePossible = true; } else { LOG.DebugFormat("No range for '{0}'", inspector.Caption); } } else { LOG.DebugFormat("No selection for '{0}'", inspector.Caption); } } else { LOG.DebugFormat("No HTML editor for '{0}'", inspector.Caption); } } catch (Exception e) { // Continue with non inline image LOG.Warn("Error pasting HTML, most likely due to an ACCESS_DENIED as the user clicked no.", e); } } // Create the attachment (if inlined the attachment isn't visible as attachment!) using (Attachment attachment = mailItem.Attachments.Add(tmpFile, OlAttachmentType.olByValue, inlinePossible ? 0 : 1, attachmentName)) { if (outlookVersion.Major >= OUTLOOK_2007) { // Add the content id to the attachment, this only works for Outlook >= 2007 try { PropertyAccessor propertyAccessor = attachment.PropertyAccessor; propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID); } catch { } } } } catch (Exception ex) { LOG.WarnFormat("Problem while trying to add attachment to Item '{0}' : {1}", inspector.Caption, ex); return(false); } try { inspector.Activate(); } catch (Exception ex) { LOG.Warn("Problem activating inspector: ", ex); return(false); } LOG.Debug("Finished!"); return(true); }