在文本框中的字符之间画一条静态线

本文关键字:一条 静态 之间 字符 文本 | 更新日期: 2023-09-27 18:18:59

我有一个文本框。我希望用户能够在里面点击;当他这样做时,一个红色的标记线应该出现在最接近点击位置的两个字符之间,并保持在这里。用户可以多次这样做。

我是新的WPF,但我想,在Winforms,我将不得不破解一个混乱的OnRender方法。到目前为止,一切正常。

我真正想知道的是:如何让两个最接近点击位置的字符?

我正准备做像素检查,但是看起来很重

在文本框中的字符之间画一条静态线

你可以试试:textBox.GetCharacterIndexFromPoint(point, true);

我找到了我想做的事情,这比我想象的要简单得多(尽管找到实际的方法是一种痛苦)。

只需将此处理程序添加到文本框的SelectionChanged事件中:

private void placeMarker(object sender, RoutedEventArgs e)
{
    // txt_mark is your TextBox
    int index = txt_mark.CaretIndex;
    // I don't want the user to be able to place a marker at index = 0 or after the last character
    if (txt_mark.Text.Length > first && first > 0)
    {
        Rect rect = txt_mark.GetRectFromCharacterIndex(first);
        Line line = new Line();
        // If by any chance, your textbox is in a scroll view,
        // use the scroll view's margin instead
        line.X1 = line.X2 = rect.Location.X + txt_mark.Margin.Left;
        line.Y1 = rect.Location.Y + txt_mark.Margin.Top;
        line.Y2 = rect.Bottom + txt_mark.Margin.Top;
        line.HorizontalAlignment = HorizontalAlignment.Left;
        line.VerticalAlignment = VerticalAlignment.Top;
        line.StrokeThickness = 1;
        line.Stroke = Brushes.Red;
        // grid1 or any panel you have
        grid1.Children.Add(line);
        // set the grid position of the line to txt_mark's (or the scrollview's if there is one)
        Grid.SetRow(line, Grid.GetRow(txt_mark));
        Grid.SetColumn(line, Grid.GetColumn(txt_mark));
    }
}

您可能需要添加一些字距,或者只是增加标记的字体大小,以不影响可读性。