Cursor Position of WebBrowser control

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Is it posible to get/set the cursor position of the webbrowser control? With
a regular text box you can use the SelectionStart property. Any help would
be greatly appreciated.
 
Hi,

The browser is not like a regular TextBox. For one thing, it renders HTML, so it shouldn't be surprising that it works differently.
In order to modify or retrieve information about the cursor position you have to use a TextRange object, which provides information
about the current selection in the document.

Add a reference in your project to the Microsoft.mshtml assembly (It's a PIA that I believe ships with Office 2003. I think there
is an older COM library that you can reference instead but I can't remember its name right now).

Use the following code to get a TextRange object that represents the current selection:

IHTMLDocument2 document = (IHTMLDocument2) webBrowser1.Document.DomDocument;

if (document.selection.type == "text")
{
IHTMLTxtRange range = (IHTMLTxtRange) document.selection.createRange();
IHTMLTextRangeMetrics metrics = (IHTMLTextRangeMetrics) range;

// Here are some ways to read and manipulate the range position:

// Get the location of the bounding rectangle of the text range relative to its parent element
Point clientLocation = new Point(metrics.boundingLeft, metrics.boundingTop);

// Collapse the TextRange into a cursor ( | ) and move it to the specified point, relative to the window:
range.moveToPoint(10, 10);
}

TextRange object on MSDN:
http://msdn.microsoft.com/library/d...hor/dhtml/reference/objects/obj_textrange.asp
 
Awesome Thanks! Would you happen to know how to override the paste event in
the control?

Talk to you soon.

Jason Smith
 
Hi Jason,

If you want managed code invoked when the user pastes something into the document:

// I'm using an anonymous method here because the body is so small, but you can use a real method if you'd like
webBrowser1.Document.AttachEventHandler("onpaste", delegate(object sender, EventArgs e)
{
MessageBox.Show(this, "Pasted!");
});


If instead you are looking for a way to programmatically paste something into the current selection or a text range:

Paste Command on MSDN:
http://msdn.microsoft.com/library/d...op/author/dhtml/reference/constants/paste.asp

You can use the Paste command on the TextRange you created in my previous code sample:

// Paste the contents of the clipboard into the text range:
range.execCommand("Paste", false, null);
 
Back
Top