Hit-Testing

The C1RichTextBox supports hyperlinks, which provide a standard mechanism for implementing user interactivity. In some cases, you may want to go beyond that and provide additional, custom mouse interactions. For example, you may want to apply some custom formatting or show a context menu when the user clicks an element.

To enable these scenarios, the C1RichTextBox exposes ElementMouse* events and a GetPositionFromPoint method.

If all you need to know is the element that triggered the mouse event, you can get it from the source parameter in the event handler. If you need more detailed information (the specific word that was clicked within the element for example), then you need the GetPositionFromPoint method. GetPositionFromPoint takes a point in client coordinates and returns a C1TextPosition object that expresses the position in document coordinates.

The C1TextPosition object has two main properties: Element and Offset. The Element property represents an element within the document; Offset is a character index (if the element is a C1Run) or the index of the child element at the given point.

For example, the code below creates a C1RichTextBox and attaches a handler to the ElementMouseLeftButtonDown event:

      Visual Basic

      C#

The event handler below toggles the FontWeight property for the entire element that was clicked. This could be a word, a sentence, or a whole paragraph:

      Visual Basic

      C#

The code gets the element that was clicked by casting the sender parameter to a C1Run object.

If you wanted to toggle the FontWeightvalue of a single word instead, then you would need to determine which character was clicked and expand the selection to the whole word. This is where the GetPositionFromPoint method becomes necessary. Here is a revised version of the event handler that accomplishes that:

      Visual Basic

      C#

Notice that the FontWeight property returns a nullable value. If the range contains a mix of values for this attribute, the property returns null. The code used to toggle the FontWeight property is the same we used earlier when implementing the formatting toolbar.


Send us comments about this topic.
Copyright © GrapeCity, inc. All rights reserved.