private void button1_Click(object sender, EventArgs e) { //Document的DomDocument属性,就是该对象内部的COM对象。 IHTMLDocument2 document = (IHTMLDocument2)webBrowser1.Document.DomDocument; string keyword = txtKeyword.Text.Trim(); if (keyword == "") return; // IE的查找逻辑就是,如果有选区,就从当前选区开头+1字符处开始查找;没有的话就从页面最初开始查找。 // 这个逻辑其实是有点不大恰当的,我们这里不用管,和IE一致即可。 if (document.selection.type.ToLower() != "none") { searchRange = (IHTMLTxtRange)document.selection.createRange(); searchRange.collapse(true); searchRange.moveStart("character", 1); } else { IHTMLBodyElement body = (IHTMLBodyElement)document.body; searchRange = (IHTMLTxtRange)body.createTextRange(); } // 如果找到了,就选取(高亮显示)该关键字;否则弹出消息。 if (searchRange.findText(keyword, 1, 0)) { searchRange.select(); searchRange.scrollIntoView(); } else { MessageBox.Show("已搜索到文档结尾。"); } }
public void InsertColumnRight_InMiddle() { string cellValue = "empty"; string cellValue2 = "empty"; System.Threading.Thread t = new System.Threading.Thread(() => { var editor = new NoteEditor(); var form = CreateForm(); form.Shown += (sender, args) => { //insert table var sut = new HtmlTableHelper(editor); sut.TableInsert(new HtmlTableProperty(true)); //fill table FillTable((editor.Document.GetElementsByTagName("table")[0].DomElement) as IHTMLTable); //move inside table var body = editor.Document.Body.DomElement as IHTMLBodyElement; IHTMLTxtRange r2 = body.createTextRange() as IHTMLTxtRange; r2.findText("r0c1"); r2.select(); //modify table sut.InsertColumnRight(); form.Close(); }; form.Controls.Add(editor); form.ShowDialog(); cellValue = GetCellValue(GetTable(editor), 0, 2); cellValue2 = GetCellValue(GetTable(editor), 0, 3); }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Assert.IsTrue(string.IsNullOrEmpty(cellValue)); Assert.AreEqual("r0c2", cellValue2); }
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 { } }
public void InsertRowAbove_RowCountIncreased() { var rowCount = 0; System.Threading.Thread t = new System.Threading.Thread(() => { var editor = new NoteEditor(); var form = CreateForm(); form.Shown += (sender, args) => { //insert table editor.HTML = "Some Text There"; var body = editor.Document.Body.DomElement as IHTMLBodyElement; IHTMLTxtRange r = body.createTextRange() as IHTMLTxtRange; r.findText("Text"); r.select(); var sut = new HtmlTableHelper(editor); sut.TableInsert(new HtmlTableProperty(true)); //move inside table IHTMLTxtRange r2 = body.createTextRange() as IHTMLTxtRange; r2.findText("Text"); r2.select(); //modify table sut.InsertRowAbove(); form.Close(); }; form.Controls.Add(editor); form.ShowDialog(); rowCount = GetTable(editor).rows.length; }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Assert.AreEqual(4, rowCount); }
public void DeleteTable() { var result = ""; System.Threading.Thread t = new System.Threading.Thread(() => { var editor = new NoteEditor(); var form = CreateForm(); form.Shown += (sender, args) => { //insert table editor.HTML = "Some Text There"; var body = editor.Document.Body.DomElement as IHTMLBodyElement; IHTMLTxtRange r = body.createTextRange() as IHTMLTxtRange; r.findText("Text"); r.select(); var sut = new HtmlTableHelper(editor); sut.TableInsert(new HtmlTableProperty(true)); //move inside table IHTMLTxtRange r2 = body.createTextRange() as IHTMLTxtRange; r2.findText("Text"); r2.select(); //modify table sut.DeleteTable(); form.Close(); }; form.Controls.Add(editor); form.ShowDialog(); result = editor.HTML; }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Assert.IsFalse(result.ToLower().Contains("table")); }
private bool FindString(HtmlElement elem, string str) { bool strFound = false; IHTMLTxtRange rng = null; try { if (rng != null) { rng.collapse(false); strFound = rng.findText(str, 1000000000, 0); if (strFound) { rng.select(); rng.scrollIntoView(true); } } if (rng == null) { IHTMLDocument2 doc = elem.Document.DomDocument as IHTMLDocument2; IHTMLBodyElement body = doc.body as IHTMLBodyElement; rng = body.createTextRange(); rng.moveToElementText(elem.DomElement as IHTMLElement); strFound = rng.findText(str, 1000000000, 0); if (strFound) { rng.select(); rng.scrollIntoView(true); } } } catch { } return(strFound); }
/// <summary> /// Inserts an image in the document /// </summary> /// <param name="src">The source of the image (file path or URL)</param> /// <param name="id">The ID of the image</param> /// <param name="border">The border size</param> /// <param name="altText">Alternative text</param> /// <param name="width">Width of the image</param> /// <param name="height">Height of the image</param> public void InsertImage(string src, string id, int border = 0, string altText = null, int width = 0, int height = 0) { if (src == null) { throw new ArgumentNullException("You must specify the image source!"); } if (id == null) { throw new ArgumentNullException("You must specify the image ID!"); } IHTMLTxtRange selection = this.document.selection.createRange() as IHTMLTxtRange; selection.pasteHTML("<img src=\"" + src + "\" id=\"" + id + "\" style=\"position:absolute\" />"); IHTMLImgElement image = GetElementById(id) as IHTMLImgElement; if (border != 0) { (image as IHTMLElement).style.border = border.ToString() + "px solid #000000"; } if (altText != null) { image.alt = altText; } if (width != 0) { (image as IHTMLElement).style.width = width.ToString(); } if (height != 0) { (image as IHTMLElement).style.height = height.ToString(); } imagePaths.Add(src); MakeInsertedElementMovable(); }
public void ChangeFontColor(string color) { if (this.GetSelectedTextStyle() != null) { if (this.GetSelectedElementType() == "BODY") { IHTMLTxtRange range = this.document.selection.createRange() as IHTMLTxtRange; string selectedText = range.text; range.execCommand("Delete", false, null); range.pasteHTML("<p>" + selectedText + "</p>"); range.select(); this.ChangeFontColor(color); } else { this.GetSelectedTextStyle().color = color; } } else { this.document.body.style.color = color; } }
private void cmdOK_Click(object sender, System.EventArgs e) { if (tabControl1.SelectedTab == tabBrowser) { IHTMLDocument2 doc2 = browser.Document.DomDocument as IHTMLDocument2; IHTMLTxtRange range = doc2.selection.createRange() as IHTMLTxtRange; plainTextSelection = range.text; fullHtmlText = browser.DocumentText; HTMLInputFinder helper = new HTMLInputFinder(); helper.SearchTargetHTML = fullHtmlText; helper.SearchFor = range.htmlText; if (helper.Find()) { htmlTextSelection = helper.FoundHTML; fullHtmlText = browser.DocumentText; } else { DialogResult userAction = MessageBox.Show("Note: HTML imported may be different from original HTML on the actual web page", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); if (userAction == DialogResult.OK) { plainTextSelection = string.Empty; htmlTextSelection = range.htmlText; fullHtmlText = browser.DocumentText; Close(); } } } else { plainTextSelection = string.Empty; htmlTextSelection = txtHtmlView.SelectedText; fullHtmlText = browser.DocumentText; } Close(); }
public void GetTableProperties() { var tableProperties = new HtmlTableProperty(false); System.Threading.Thread t = new System.Threading.Thread(() => { var editor = new NoteEditor(); var form = CreateForm(); form.Shown += (sender, args) => { //insert table var sut = new HtmlTableHelper(editor); sut.TableInsert(new HtmlTableProperty(true)); //fill table FillTable((editor.Document.GetElementsByTagName("table")[0].DomElement) as IHTMLTable); //move inside table var body = editor.Document.Body.DomElement as IHTMLBodyElement; IHTMLTxtRange r2 = body.createTextRange() as IHTMLTxtRange; r2.findText("r2c2"); r2.select(); //modify table sut.DeleteRow(); tableProperties = sut.GetTableProperties(GetTable(editor)); form.Close(); }; form.Controls.Add(editor); form.ShowDialog(); }); t.SetApartmentState(System.Threading.ApartmentState.STA); t.Start(); t.Join(); Assert.AreEqual(2, tableProperties.TableRows); }
private string GetHtmlDocSelectedContent(mshtml.IHTMLDocument2 htmlDoc) { 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); } return(range.htmlText); }
//Registers clipboard formats that we can handle //Registered Dragdrop formats //private short m_CFHTML = 0; //private short m_CFRTF = 0; //private short m_CFURL = 0; //private short m_CFNETRESOURCE = 0; //private short m_CFUNTRUSTEDDRAGDROP = 0; //private short m_CFFILEGROUPDESCRIPTOR = 0; //private short m_CFFILECONTENTS = 0; //private void RegisterClipboardFormatsForDragDrop() //{ // m_CFHTML = (short)WinApis.RegisterClipboardFormat("HTML Format"); // m_CFRTF = (short)WinApis.RegisterClipboardFormat("Rich Text Format"); // m_CFFILEGROUPDESCRIPTOR = (short)WinApis.RegisterClipboardFormat("FileGroupDescriptor"); // m_CFFILECONTENTS = (short)WinApis.RegisterClipboardFormat("FileContents"); // m_CFUNTRUSTEDDRAGDROP = (short)WinApis.RegisterClipboardFormat("UntrustedDragDrop"); // m_CFURL = (short)WinApis.RegisterClipboardFormat("UniformResourceLocator"); // m_CFNETRESOURCE = (short)WinApis.RegisterClipboardFormat("Net Resource"); //} private void InternalFreeWB() { if( (!DesignMode) && (m_WBUnknown != null) ) { //Get connectionpointcontainer IConnectionPointContainer cpCont = m_WBUnknown as IConnectionPointContainer; //Find connection point if (cpCont != null) { Guid guid = typeof(DWebBrowserEvents2).GUID; IConnectionPoint m_WBConnectionPoint = null; cpCont.FindConnectionPoint(ref guid, out m_WBConnectionPoint); //UnAdvice if ((m_WBConnectionPoint != null) && (m_dwCookie > 0)) m_WBConnectionPoint.Unadvise(m_dwCookie); } //UI and Inplace deactivate if (m_WBOleInPlaceObject != null) { m_WBOleInPlaceObject.UIDeactivate(); m_WBOleInPlaceObject.InPlaceDeactivate(); } //Disconnect from ole if (m_WBOleObject != null) { m_WBOleObject.Close((uint)OLEDOVERB.OLECLOSE_NOSAVE); m_WBOleObject.SetClientSite(null); } } if (m_txtrange != null) { Marshal.ReleaseComObject(m_txtrange); m_txtrange = null; } if (m_WBOleCommandTarget != null) { Marshal.ReleaseComObject(m_WBOleCommandTarget); m_WBOleCommandTarget = null; } if (m_WBWebBrowser2 != null) { Marshal.ReleaseComObject(m_WBWebBrowser2); m_WBWebBrowser2 = null; } if (m_WBOleInPlaceObject != null) { Marshal.ReleaseComObject(m_WBOleInPlaceObject); m_WBOleCommandTarget = null; } if (m_WBOleObject != null) { Marshal.ReleaseComObject(m_WBOleObject); m_WBOleObject = null; } if (m_WBUnknown != null) { Marshal.ReleaseComObject(m_WBUnknown); m_WBUnknown = null; } if (m_WantHtmlDocumentEvents) { m_TopLevelHtmlDocumentevents.DisconnectHtmlEvents(); DisconnectHtmlDocumentEvents(); } if (m_WantHtmlWindowEvents) { m_TopLevelHtmlWindowEvents.DisconnectHtmlEvents(); DisconnectHtmlWindowEvnets(); } if (m_Subclassed) { StopSubclass(); } }
void Document_MouseMove(object sender, HtmlElementEventArgs e) { try { mshtml.IHTMLDocument2 ihtd = this.DomDocument as IHTMLDocument2; IHTMLTxtRange ihtr = ihtd.selection.createRange() as mshtml.IHTMLTxtRange; if (ihtr.text != null) { this.searchText = ihtr.text; } HtmlElement he = this.Document.GetElementFromPoint(e.MousePosition); if (he == null) { return; } string htmlCode = he.OuterHtml; if (htmlCode.IndexOf("A") == 1) { Res[] rc = (Res[])this.Tag; //ResCollection rrr = new ResCollection(); Res[] resData = new Res[this.ThreadData.GetRescount + 1]; StringBuilder sb = new StringBuilder(); if (htmlCode.IndexOf("method:Extract", StringComparison.CurrentCultureIgnoreCase) != -1) { string method = String.Empty; if (htmlCode.IndexOf("発信元") == -1) { method = new System.Text.RegularExpressions.Regex(@"method:Extract[(](?<type>..),(?<id>.{1,15})[)]", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(htmlCode).Groups["id"].Value; } else { method = new System.Text.RegularExpressions.Regex(@"method:Extract[(](?<type>..),(?<id>.{1,25})[)]", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(htmlCode).Groups["id"].Value; } //foreach (Res item in rc) //{ // if (method.Replace("ID:", "") == item.ID) // { // rrr.Add(item); // } //} int c = 0; for (int i = 0; i < rc.Length; i++) { if (method == rc[i].ID) { resData[c] = rc[i]; c++; } } foreach (Res item in resData) { if (String.IsNullOrEmpty(item.Sentence)) { break; } sb.Append(ResConvert.SimpleConvertCore(item)); } //MessageBox.Show(sb.ToString().Replace("<br>","\n")); //hp.Show(sb.ToString()); hp.Show(sb.ToString()); //if (popupChild == -1) //{ // nowPopup = true; // popupPlaces.Add(new System.Drawing.Point(MousePosition.X, MousePosition.Y)); //} //else if (popupChild == 0) //{ // popupPlaces.Add(MousePosition); // popupChild++; //} //else //{ // popupPlaces.Add(MousePosition); // popupChild++; //} } else { if (htmlCode.IndexOf("#") == 9 || htmlCode.IndexOf("#") == 20) { string data = new System.Text.RegularExpressions.Regex(@"<A href=(""about:blank#""|""#"")>>>(?<res>\d*)</A>").Match(htmlCode).Groups["res"].Value; int resNumber = int.Parse(data); resNumber--; //ResConvert.SimpleConvertCore(rc[resNumber]); //sb.Append(rc[resNumber].Index).Append(": ").Append(rc[resNumber].Name).Append("[" + rc[resNumber].Mail + "]").Append(rc[resNumber].Date + "<br>").Append(rc[resNumber].Sentence + "<br>"); //hp.Show(sb.ToString()); hp.Show(ResConvert.SimpleConvertCore(rc[resNumber])); } } } this.HidePopup(); } catch { return; } }
/// <summary> /// Move to range. /// </summary> /// <param name="textRange"></param> public void MoveToTextRange(IHTMLTxtRange textRange) { MarkupServices.MovePointersToRange(textRange, Start, End); }
/// <summary> /// Positions pointers at the edges of an existing range. /// </summary> /// <param name="start">the pointer positioned at the start of the range</param> /// <param name="end">the pointer position at the end of the range</param> /// <param name="range">the text range to move</param> public void MoveRangeToPointers(MarkupPointer start, MarkupPointer end, IHTMLTxtRange range) { MarkupServices.MoveRangeToPointers(start.PointerRaw, end.PointerRaw, range); }
/// <summary> /// Create a MarkupRange from a TextRange. /// </summary> /// <param name="textRange"></param> /// <returns></returns> public MarkupRange CreateMarkupRange(IHTMLTxtRange textRange) { MarkupPointer Begin = CreateMarkupPointer(); MarkupPointer End = CreateMarkupPointer(); End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right; MovePointersToRange(textRange, Begin, End); MarkupRange markupRange = new MarkupRange(Begin, End, this); return markupRange; }
private static IHTMLTxtRange SelectLastPartialWord(IHTMLTxtRange selObj) { selObj.moveStart("word", -1); return(selObj); }
//эта функция - на удаление форматирования текста из середины. Например, <s>testing</s> станет <s>te</s>sti<s>ng</s>. + плюшка для sub-sup тегов private void removeFormatFromMiddle(ref string tagName, IHTMLTxtRange range, string antiTagName = "", string attributes = "", string antiAttributes = "") { IHTMLElement el = range.parentElement(); bool need = false; while (el.tagName != "BODY") { if (el.tagName == antiTagName || el.tagName == tagName) { need = true; antiAttributes = antiAttributes == "fontSize" ? "style=\"FONT-SIZE: " + el.style.fontSize + "\"" : ""; break; } el = el.parentElement; } if (range.htmlText[0] != '<' && need) { string htmlCode = range.htmlText; if (el.tagName == antiTagName) { range.pasteHTML("</" + antiTagName + "><" + tagName + " " + attributes + ">" + htmlCode + "</" + tagName + "><" + antiTagName + " " + antiAttributes + ">"); tagName = antiTagName; } else if (el.tagName == tagName) { range.pasteHTML("</" + tagName + ">" + htmlCode + "<" + tagName + "/>"); } string elemHtmlCode = el.outerHTML; int startIndex = elemHtmlCode.LastIndexOf("</" + tagName + ">", elemHtmlCode.Length - ("</" + tagName + ">").Length);//ищет с конца, не берет тег самого родительского элемента elemHtmlCode = elemHtmlCode.Remove(startIndex, ("</" + tagName + ">").Length); try { el.outerHTML = elemHtmlCode; } catch { } tagName = "Success"; } }
public void SetSelectionFontSize(float size) { try { //get selected range IHTMLTxtRange range = htmlDoc.selection.createRange() as IHTMLTxtRange; //range could be null if selection type is not text if (range == null) { return; } //expand to a word if nothing selected if (string.IsNullOrEmpty(range.htmlText)) { range.expand("word"); if (string.IsNullOrEmpty(range.htmlText)) { return; //return if still null } } //get the parent of selected range IHTMLElement elem = range.parentElement() as IHTMLElement; //check if selected range contains parent element bool isElement = !elem.tagName.Equals("BODY") && ((range.text == null && elem.outerText == null) || (range.text != null && range.text.Equals(elem.outerText))); if (isElement) { //clear font size for all children foreach (var c in (elem.children as IHTMLElementCollection)) { ClearFontSize(c as IHTMLElement); } //set font size for the element IHTMLStyle style = elem.style as IHTMLStyle; style.fontSize = size + "pt"; } else { //clear font size for all elements inside the selection var body = htmlDoc.body as IHTMLBodyElement; foreach (IHTMLElement childElem in (elem.children as IHTMLElementCollection)) { IHTMLTxtRange r = body.createTextRange() as IHTMLTxtRange; r.moveToElementText(childElem); if (range.inRange(r)) { ClearFontSize(childElem); } } //set font size by surrounding with span range.pasteHTML("<span style='font-size:" + size + "pt'>" + range.htmlText + "</span>"); } } catch (Exception e) { System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + ": NoteEdiitor.SetFontSize" + e.Message); System.Diagnostics.Trace.WriteLine(e.StackTrace); } }
/// <summary> /// Inserts a new hyperlink in the document /// </summary> /// <param name="text">The title of the hyperlink</param> /// <param name="url">The URL of the hyperlink</param> public void InsertHyperlink(string text, string url) { IHTMLTxtRange range = this.document.selection.createRange() as IHTMLTxtRange; range.pasteHTML("<a href=\"" + url + "\">" + text + "</a>"); }
/// <summary> /// Creates an HTMLDataObject from an IHTMLDocument2 and an IHTMLSelectionObject. /// </summary> /// <param name="document">The document containing the selection</param> /// <param name="selection">The selection from which to create the HTMLDataObject</param> /// <returns>An HTMLDataObject, null if no HTMLDataObject could be created.</returns> public HTMLDataObject(IHTMLTxtRange textRange, IHTMLDocument2 document) { IDataObject = new DataObject(DataFormats.Html, GetHTMLFormatString(textRange.htmlText, document.url)); }
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 void subSubInsertTag(IHTMLTxtRange range, string tagName, string antiTagName) { string htmlCode = range.htmlText; if (htmlCode.Contains(antiTagName) || htmlCode.Contains(tagName)) { htmlCode = htmlCode.Replace("<" + antiTagName + ">", ""); htmlCode = htmlCode.Replace("</" + antiTagName + ">", ""); htmlCode = htmlCode.Replace("<" + tagName + ">", ""); htmlCode = htmlCode.Replace("</" + tagName + ">", ""); htmlDocument.selection.clear(); } insertTag(tagName, htmlCode, range); }
private string deleteTag(string tagName, IHTMLTxtRange range = null, string formatStr = "") { string htmlCode = formatStr != "" ? formatStr : (range != null ? range.htmlText : ""); try { htmlCode = htmlCode.Replace("</" + tagName + ">", ""); htmlCode = htmlCode.Replace("\n", ""); htmlCode = htmlCode.Replace("\r", ""); while (true) { int startIndex = htmlCode.IndexOf("<" + tagName); if (startIndex == -1) break; int endIndex = htmlCode.IndexOf('>', startIndex); htmlCode = htmlCode.Remove(startIndex, endIndex - startIndex + 1);// +1 - для удаления '>' } if (formatStr == "" && range != null) { htmlDocument.selection.clear(); range.pasteHTML(htmlCode); } } catch { } return htmlCode; }
/// <summary> /// Positions pointers at the edges of an existing range. /// </summary> /// <param name="range">the text range to move to</param> /// <param name="start">the pointer to position at the start of the range</param> /// <param name="end">the pointer to position at the end of the range</param> public void MovePointersToRange(IHTMLTxtRange range, MarkupPointer start, MarkupPointer end) { MarkupServices.MovePointersToRange(range, start.PointerRaw, end.PointerRaw); }
private void insertTag(string tagName, string htmlCode, IHTMLTxtRange range, string attributes = "") { if (htmlDocument.selection.type != "None") htmlDocument.selection.clear(); range.pasteHTML("<" + tagName + " " + attributes + ">" + htmlCode + "</" + tagName + ">"); }
internal Range(IHTMLTxtRange range) { msHtmlTxRange = range; }
private int HighlightKeyword() { int matches = -1; if (!string.IsNullOrEmpty(messageProvider.Keyword)) { const string strbg = "BackColor"; const string strf = "ForeColor"; const string sword = "Character"; const string stextedit = "Textedit"; //You may be tempted to use Color.Yellow.ToArgb(). But, //the value returned includes the A value which //causes confusion for MSHTML. i.e. Color.Cyan is interpreted as yellow int background = MakeRGB(Color.FromName("Yellow")); //int foreground = MakeRGB(Color.FromName("Yellow")); IHTMLDocument2 document = webBrowser.Document.DomDocument as IHTMLDocument2; if (document != null) { IHTMLElement pElem = document.body; IHTMLBodyElement pBodyelem = pElem as IHTMLBodyElement; if (pBodyelem == null) { return(matches); } IHTMLTxtRange range = pBodyelem.createTextRange(); if (range == null) { return(matches); } //IHTMLSelectionObject currentSelection = document.selection; //IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; IHTMLTxtRange firstRange = null; while (range.findText(messageProvider.Keyword, messageProvider.Keyword.Length, 0)) { if (matches == -1) { matches = 0; firstRange = range.duplicate(); } if (background != 0) { range.execCommand(strbg, false, background); } //if (foreground != 0) //range.execCommand(strf, false, foreground); range.moveStart(sword, 1); range.moveEnd(stextedit, 1); matches += 1; } if (firstRange != null) { firstRange.scrollIntoView(true); } } } return(matches); }
//remove all misspellings from tracker and clear their highlights //used when turning spell checking on and off public void Reset() { _timer.Enabled = false; stagingTextRange = null; _workerQueue.Clear(); IHighlightSegmentRaw[] allWords = _tracker.ClearAllSegments(); for (int i = 0; i < allWords.Length; i++) { _highlightRenderingServices.RemoveSegment(allWords[i]); } }
public static bool AdjustMarkupRange(MarkupRange range, int offset, int length) { IHTMLTxtRange stagingTextRange = range.ToTextRange(); return(AdjustMarkupRange(ref stagingTextRange, range, offset, length)); }
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); }
/// <summary> /// Method to insert a basic table /// Will honour the existing table if passed in /// </summary> private void ProcessTable(IHTMLTable table, HtmlTableProperty tableProperties) { try { // obtain a reference to the body node and indicate table present var document = ContentUtils.GetFocusedHtmlDocument(); var bodyNode = document?.body; bool tableCreated = false; // ensure a table node has been defined to work with if (table.IsNull()) { // create the table and indicate it was created table = (IHTMLTable)document.createElement("<table>"); tableCreated = true; } // define the table border, width, cell padding and spacing table.border = tableProperties.BorderSize; if (tableProperties.TableWidth > 0) { table.width = (tableProperties.TableWidthMeasurement == MeasurementOption.Pixel) ? string.Format("{0}", tableProperties.TableWidth) : string.Format("{0}%", tableProperties.TableWidth); } else { table.width = string.Empty; } table.align = tableProperties.TableAlignment != HorizontalAlignOption.Default ? tableProperties.TableAlignment.ToString().ToLower() : string.Empty; table.cellPadding = tableProperties.CellPadding.ToString(CultureInfo.InvariantCulture); table.cellSpacing = tableProperties.CellSpacing.ToString(CultureInfo.InvariantCulture); // define the given table caption and alignment string caption = tableProperties.CaptionText; IHTMLTableCaption tableCaption = table.caption; if (!caption.IsNullOrEmpty()) { // ensure table caption correctly defined if (tableCaption.IsNull()) { tableCaption = table.createCaption(); } ((IHTMLElement)tableCaption).innerText = caption; if (tableProperties.CaptionAlignment != HorizontalAlignOption.Default) { tableCaption.align = tableProperties.CaptionAlignment.ToString().ToLower(); } if (tableProperties.CaptionLocation != VerticalAlignOption.Default) { tableCaption.vAlign = tableProperties.CaptionLocation.ToString().ToLower(); } } else { // if no caption specified remove the existing one if (!tableCaption.IsNull()) { // prior to deleting the caption the contents must be cleared ((IHTMLElement)tableCaption).innerText = null; table.deleteCaption(); } } // determine the number of rows one has to insert int numberRows, numberCols; if (tableCreated) { numberRows = Math.Max((int)tableProperties.TableRows, 1); } else { numberRows = Math.Max((int)tableProperties.TableRows, 1) - table.rows.length; } // layout the table structure in terms of rows and columns table.cols = tableProperties.TableColumns; if (tableCreated) { // this section is an optimization based on creating a new table // the section below works but not as efficiently numberCols = Math.Max((int)tableProperties.TableColumns, 1); // insert the appropriate number of rows IHTMLTableRow tableRow; for (int idxRow = 0; idxRow < numberRows; idxRow++) { tableRow = (IHTMLTableRow)table.insertRow(); // add the new columns to the end of each row for (int idxCol = 0; idxCol < numberCols; idxCol++) { tableRow.insertCell(); } } } else { // if the number of rows is increasing insert the decrepency if (numberRows > 0) { // insert the appropriate number of rows for (int idxRow = 0; idxRow < numberRows; idxRow++) { table.insertRow(); } } else { // remove the extra rows from the table for (int idxRow = numberRows; idxRow < 0; idxRow++) { table.deleteRow(table.rows.length - 1); } } // have the rows constructed // now ensure the columns are correctly defined for each row IHTMLElementCollection rows = table.rows; foreach (IHTMLTableRow tableRow in rows) { numberCols = Math.Max((int)tableProperties.TableColumns, 1) - tableRow.cells.length; if (numberCols > 0) { // add the new column to the end of each row for (int idxCol = 0; idxCol < numberCols; idxCol++) { tableRow.insertCell(); } } else { // reduce the number of cells in the given row // remove the extra rows from the table for (int idxCol = numberCols; idxCol < 0; idxCol++) { tableRow.deleteCell(tableRow.cells.length - 1); } } } } // if the table was created then it requires insertion into the DOM // otherwise property changes are sufficient if (tableCreated) { // table processing all complete so insert into the DOM var tableNode = (IHTMLDOMNode)table; var tableElement = (IHTMLElement)table; IHTMLTxtRange textRange = ContentUtils.GetTextSelectionObject(); // final insert dependant on what user has selected if (!textRange.IsNull()) { // text range selected so overwrite with a table try { string selectedText = textRange.text; if (!selectedText.IsNull()) { // place selected text into first cell var tableRow = (IHTMLTableRow)table.rows.item(0, null); ((IHTMLElement)tableRow.cells.item(0, null)).innerText = selectedText; } textRange.pasteHTML(tableElement.outerHTML); } catch (RemotingException) { } catch (UnauthorizedAccessException) { } } else { IHTMLControlRange controlRange = ContentUtils.GetControlSelectionObject(); if (!controlRange.IsNull()) { // overwrite any controls the user has selected try { // clear the selection and insert the table // only valid if multiple selection is enabled for (int idx = 1; idx < controlRange.length; idx++) { controlRange.remove(idx); } controlRange.item(0).outerHTML = tableElement.outerHTML; // this should work with initial count set to zero // controlRange.add((mshtmlControlElement)table); } catch (RemotingException) { } catch (UnauthorizedAccessException) { } } else { // insert the table at the end of the HTML ((IHTMLDOMNode)bodyNode).appendChild(tableNode); } } } else { // table has been correctly defined as being the first selected item // need to remove other selected items IHTMLControlRange controlRange = ContentUtils.GetControlSelectionObject(); if (!controlRange.IsNull()) { // clear the controls selected other than than the first table // only valid if multiple selection is enabled for (int idx = 1; idx < controlRange.length; idx++) { controlRange.remove(idx); } } } } catch (RemotingException) { } catch (UnauthorizedAccessException) { } } //ProcessTable
private static Rectangle GetLabelCoodsByInsertingElement( IHTMLTxtRange label, IHTMLDocument2 document ) { // A bit of a hack: create an HTML element around the selected // text and get the location of that element from document.all[]. // Note that this is actually pretty common hack for search/highlight functions: // http://www.pcmag.com/article2/0,2704,1166598,00.asp // http://www.codeproject.com/miscctrl/chtmlview_search.asp // http://www.itwriting.com/phorum/read.php?3,1561,1562,quote=1 // Save the text string oldText = label.text; // NB: Because of a weird bug in IHTMLElement.outerHTML (see test case // ProximityTests.ShouldNotDuplicateSpanElementsPrecedingTheText) we need // to use the text and not htmlText of the label. // If there's any HTML in the label it will be lost when the test completes // so check here and throw an exception // TODO: It might still be possible to fix this by saving document.body.outerHTML // at start-up and replacing that entirely at the completion of each search pass // but that seems messy and resource intensive. if( oldText != label.htmlText ) { throw new ArgumentException( "The text to match for the field element should not have any HTML in it.", "labelText" ); } // Create a unique ID const int maxTries = 1000; const string rootId = "ProximityTextConstraintId"; int i = 0; string id = rootId + i; while( i < maxTries && document.all.item(id, null) != null ) { id = rootId + ++i; } if( i >= maxTries ) return new Rectangle(); // Add a span tag the the HTML string code = String.Format( "<span id=\"{0}\">{1}</span>", id, oldText ); label.pasteHTML( code ); // Get the element's position IHTMLElement element = (IHTMLElement)document.all.item( id, null ); // Build the bounds Rectangle bounds = GetIHTMLElementBounds( element ); // Restore the HTML // This only seems to work if the text is not immediately preceded by a span element. // In that case it fails because it seems to grab the parent span element when identifying // the 'outerHTML' and then duplicates that for each pass. element.outerHTML = oldText; // Doesn't work: Does not replace the text when pasted into place despite suggestions in implementations // listed above //label.pasteHTML( oldHtml ); return bounds; }
public void WrapSelection(string tag) { IHTMLTxtRange range = doc.selection.createRange() as IHTMLTxtRange; range.pasteHTML(string.Format("<{0}>{1}</{0}>", tag, range.htmlText)); }
/// <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); }
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); }
//Find + Find and highlight public bool FindInPage(string sFind, bool DownWard, bool MatchWholeWord, bool MatchCase, bool ScrollIntoView) { bool success = false; if (m_WBWebBrowser2 == null) return success; if (sFind.Length == 0) { m_sLastSearch = ""; m_txtrange = null; return success; } else m_sLastSearch = sFind; int searchdir = (DownWard) ? 1000000 : -1000000; int searchcase = 0; //default //Set up search case if ((MatchWholeWord) && (MatchCase)) searchcase = 6; else if (MatchWholeWord) searchcase = 2; else if (MatchCase) searchcase = 4; if (m_txtrange != null) { if (sFind == m_sLastSearch) { if (DownWard) m_txtrange.collapse(false); else m_txtrange.collapse(true); } else m_txtrange = null; } IHTMLDocument2 pDoc2 = GetActiveDocument(); if (pDoc2 == null) return success; IHTMLElement pElem = pDoc2.body; IHTMLBodyElement pBodyelem = pElem as IHTMLBodyElement; if (pBodyelem == null) return success; if (m_txtrange == null) m_txtrange = pBodyelem.createTextRange(); if (m_txtrange == null) return success; success = m_txtrange.findText(sFind, searchdir, searchcase); if (success) { m_txtrange.select(); if (ScrollIntoView) m_txtrange.scrollIntoView(true); } return success; }
private static Rectangle GetLabelCoodsByInsertingElement(IHTMLTxtRange label, IHTMLDocument2 document) { // A bit of a hack: create an HTML element around the selected // text and get the location of that element from document.all[]. // Note that this is actually pretty common hack for search/highlight functions: // http://www.pcmag.com/article2/0,2704,1166598,00.asp // http://www.codeproject.com/miscctrl/chtmlview_search.asp // http://www.itwriting.com/phorum/read.php?3,1561,1562,quote=1 // Save the text string oldText = label.text; // NB: Because of a weird bug in IHTMLElement.outerHTML (see test case // ProximityTests.ShouldNotDuplicateSpanElementsPrecedingTheText) we need // to use the text and not htmlText of the label. // If there's any HTML in the label it will be lost when the test completes // so check here and throw an exception // TODO: It might still be possible to fix this by saving document.body.outerHTML // at start-up and replacing that entirely at the completion of each search pass // but that seems messy and resource intensive. if (oldText != label.htmlText) { throw new ArgumentException("The text to match for the field element should not have any HTML in it.", "labelText"); } // Create a unique ID const int maxTries = 1000; const string rootId = "ProximityTextConstraintId"; int i = 0; string id = rootId + i; while (i < maxTries && document.all.item(id, null) != null) { id = rootId + ++i; } if (i >= maxTries) { return(new Rectangle()); } // Add a span tag the the HTML string code = String.Format("<span id=\"{0}\">{1}</span>", id, oldText); label.pasteHTML(code); // Get the element's position IHTMLElement element = (IHTMLElement)document.all.item(id, null); // Build the bounds Rectangle bounds = GetIHTMLElementBounds(element); // Restore the HTML // This only seems to work if the text is not immediately preceded by a span element. // In that case it fails because it seems to grab the parent span element when identifying // the 'outerHTML' and then duplicates that for each pass. element.outerHTML = oldText; // Doesn't work: Does not replace the text when pasted into place despite suggestions in implementations // listed above //label.pasteHTML( oldHtml ); return(bounds); }
private static Rectangle GetTextBoundsByInsertingElement(IHTMLTxtRange textRange, IHTMLDocument2 document) { // A bit of a hack: create an HTML element around the selected // text and get the location of that element from document.all[]. // Note that this is actually pretty common hack for search/highlight functions: // http://www.pcmag.com/article2/0,2704,1166598,00.asp // http://www.codeproject.com/miscctrl/chtmlview_search.asp // http://www.itwriting.com/phorum/read.php?3,1561,1562,quote=1 // Save the text string oldHtmlText = textRange.htmlText; // Sometimes the text range contains the containing HTML element such as a SPAN tag. // eg. "<SPAN id=spanValidateCode>Code and Confirm Code must match!</SPAN>" // // This is ok. We just grab the bounds of the whole element, which happens to be the // one returned by parentElement(). if (oldHtmlText != textRange.text) { return IEElement.GetHtmlElementBounds(textRange.parentElement()); } // Create a unique ID string id = @"__WatiNTextRange_" + Guid.NewGuid(); // Add a span tag the the HTML string code = String.Format("<span id=\"{0}\">{1}</span>", id, oldHtmlText); textRange.pasteHTML(code); // Get the element's position var element = (IHTMLElement)document.all.item(id, null); // Build the bounds Rectangle bounds = IEElement.GetHtmlElementBounds(element); // Restore the HTML // This only seems to work if the text is not immediately preceded by a span element. // In that case it fails because it seems to grab the parent span element when identifying // the 'outerHTML' and then duplicates that for each pass. element.outerHTML = oldHtmlText; // Doesn't work: Does not replace the text when pasted into place despite suggestions in implementations // listed above //textRange.pasteHTML( oldHtml ); return bounds; }
/// <summary> /// Inserts a new heading in the document /// </summary> /// <param name="text">The text of the heading</param> /// <param name="size">The heading size (1 - 7)</param> public void InsertHeading(string text, int size) { IHTMLTxtRange range = this.document.selection.createRange() as IHTMLTxtRange; range.pasteHTML("<h" + size + ">" + text + "</h" + size + ">"); }
/// <summary> /// Inserts a list /// </summary> /// <param name="ordered">Indicates whether the list should be ordered or not</param> /// <param name="type">The type of the list</param> /// <param name="items">The list items</param> public void InsertList(bool ordered, ListType type, List <string> items) { StringBuilder htmlText = new StringBuilder(); string listType = string.Empty; switch (type) { case ListType.CapitalLetters: listType = "upper-alpha"; break; case ListType.CapitalRoman: listType = "upper-roman"; break; case ListType.Circle: listType = "circle"; break; case ListType.Decimal: listType = "decimal"; break; case ListType.Disc: listType = "disc"; break; case ListType.LowerLetters: listType = "lower-alpha"; break; case ListType.LowerRoman: listType = "lower-roman"; break; case ListType.Square: listType = "square"; break; } if (ordered) { htmlText.AppendLine("<ol>"); } else { htmlText.AppendLine("<ul>"); } foreach (string item in items) { htmlText.AppendLine("<li>" + item + "</li>"); } if (ordered) { htmlText.AppendLine("</ol>"); } else { htmlText.AppendLine("</ul"); } IHTMLTxtRange range = this.document.selection.createRange() as IHTMLTxtRange; range.pasteHTML(htmlText.ToString()); range.select(); if (this.GetSelectedElementType() != "BODY") { this.GetSelectedElement().parentElement.style.listStyleType = listType; } }
public IHighlightSegment UnderLineWord2(IHTMLTxtRange range) { IMarkupPointer impStart; IMarkupPointer impEnd; //Get body element IHTMLElement body = m_pDoc2.body; //Setup two markup pointers m_pMarkupServices.CreateMarkupPointer(out impStart); m_pMarkupServices.CreateMarkupPointer(out impEnd); //Move pointers to our range m_pMarkupServices.MovePointersToRange(range, impStart, impEnd); //Setup new element IHTMLElement ttelem = null; m_pMarkupServices.CreateElement((int)ELEMENT_TAG_ID.TAGID_SPAN, " ", out ttelem); //Insert new element m_pMarkupServices.InsertElement(ttelem, impStart, impEnd); //Now underline return Underline2(ttelem); }