【发布时间】:2015-10-09 00:48:55
【问题描述】:
我有一个查找下一个和上一个功能并对其进行了编辑,以便当用户在文本框中选择文本并单击“查找下一个”或“查找上一个”按钮时,查找功能将从所选字符开始索引并继续通过每个搜索结果(最初该功能不存在)。为了获取所选文本的起始索引,我创建了一个函数:
private int GetIntialCharPos(string Text)
{
int row = Variables._TextBox.GetLineIndexFromCharacterIndex(Variables._TextBox.CaretIndex);
int col = Variables._TextBox.CaretIndex - Variables._TextBox.GetCharacterIndexFromLineIndex(row);
return col;
}
查找下一个和上一个的函数如下:
private List<int> _matches;
private string _textToFind;
private bool _matchCase;
private int _matchIndex;
private void MoveToNextMatch(string textToFind, bool matchCase, bool forward)
{
if (_matches == null || _textToFind != textToFind || _matchCase != matchCase)
{
int startIndex = 0, matchIndex;
StringComparison mode = matchCase ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
_matches = new List<int>();
while (startIndex < Variables._TextBox.Text.Length && (matchIndex = Variables._TextBox.Text.IndexOf(textToFind, startIndex, mode)) >= 0)
{
_matches.Add(matchIndex);
startIndex = matchIndex + textToFind.Length;
}
_textToFind = textToFind;
_matchCase = matchCase;
_matchIndex = forward ? _matches.IndexOf(GetIntialCharPos(textToFind)) : _matches.IndexOf(GetIntialCharPos(textToFind)) - 1;
}
else
{
_matchIndex += forward ? 1 : -1;
if (_matchIndex < 0)
{
_matchIndex = _matches.Count - 1;
}
else if (_matchIndex >= _matches.Count)
{
_matchIndex = 0;
}
}
if (_matches.Count > 0)
{
Variables._TextBox.SelectionStart = _matches[_matchIndex];
Variables._TextBox.SelectionLength = textToFind.Length;
Variables._TextBox.Focus();
}
}
我的问题是,一旦用户选择了他需要搜索的文本,并通过查找下一个和上一个按钮,然后他决定从不同的索引中选择文本,而不是从选定的索引中继续搜索索引,它将保持默认的初始顺序,而不是从选定的索引开始并从中遍历每个结果。我创建了一个小的gif video here,以便您更好地了解这个问题。
如何保留选定的单词索引,以便每次用户从不同的索引中选择时,它都可以从用户选择的索引开始搜索,而不是总是从头开始。
【问题讨论】:
标签: c# search textbox selection