The TextCharCollection.GetItem method has an implementation that returns the nearest character of a given location. A TX Text Control user requested this for the DocumentTargetCollection as well. A method that returns the nearest DocumentTarget at the current input position.

We added this smart request to our list of feature requests. But as always, we try to provide work-arounds for such tasks. TX Text Control's API is very flexible and generally, all calculations are doable based on the available interface.

The following function returns the nearest DocumentTarget for a specific position:

private DocumentTarget GetNearestTarget(int Start)
{
    DocumentTarget nearestTarget = null;

    foreach (DocumentTarget target in textControl1.DocumentTargets)
    {
        if (nearestTarget == null)
        {
            nearestTarget = target;
            continue;
        }

        if (System.Math.Abs((target.Start - Start))
                <= System.Math.Abs((nearestTarget.Start - Start)))
            nearestTarget = target;
    }

    return nearestTarget;
}

The function is pretty straightforward: All targets are iterated and the distance between the input position and the target start position is compared. The target with the shortest distance is returned.