wxStyledTextCtrl 设置选择

wxStyledTextCtrl SetSelection

在下面的代码中:

void Script::OnLeftUp( wxMouseEvent& event )
{
    int currentPos = GetCurrentPos();
    int wordStartPos = WordStartPosition( currentPos, true );
    int wordEndPos=WordEndPosition(wordStartPos, true);
    wxString identifier=GetRange(wordStartPos,wordEndPos);
    SetSelection(wordStartPos, wordEndPos );
    event.Skip();
}

当我点击单词中的一个点时(例如单词是 hello,我在 el 之间左键单击),标识符被正确识别为hello。但是,只有 he 被选中,而我希望整个单词 hello 被选中。可能出了什么问题?如果位置错了,那么标识符的值应该是错误的,事实并非如此。

顺便说一下,我在 Windows 10.

上使用 wxWidgets 3.1

根据 SetSelection 的文档:

Notice that the insertion point will be moved to from by this function

不确定原因,但这似乎以某种方式影响了最终选择。您可以尝试像这样重写函数:

void Script::OnLeftUp( wxMouseEvent& event )
{
    int currentPos = GetCurrentPos();
    int wordStartPos = WordStartPosition( currentPos, true );
    int wordEndPos = WordEndPosition( currentPos, true );
    wxString identifier = GetRange( wordStartPos, wordEndPos );
    SetSelectionStart( wordStartPos );
    SetSelectionEnd( wordEndPos );
    event.Skip();
}

你想做的事情并不完全可行。在 scintilla/wxStyledTextCtrl 中,选择总是从某处运行到当前插入符位置。您正在尝试进行从当前位置之前开始并在当前位置之后结束的选择,但这是无法完成的。

此外,这基本上是双击单词时的默认行为,但双击会将插入符号移动到单词的末尾。您真的需要单击一下即可完成此操作吗?如果你真的想要,你可以使用多重选择来给出这个外观。基本上,您将有一个从单词开头到当前位置的选择,以及从当前位置到结尾的第二个选择。

将这些命令放在鼠标处理程序之前被调用的地方(可能在构造函数中),并使用此原型声明一个方法 "void SelectCurWord();"

SetSelBackground(true, wxColour(192,192,192) );
SetSelForeground(true, wxColour(0,0,0) );

SetAdditionalSelBackground( wxColor(192,192,192) );
SetAdditionalSelForeground( wxColour(0,0,0) );
SetAdditionalCaretsVisible(false);

您可以将颜色更改为任何您想要的颜色,但要确保主要选择和附加选择使用相同的颜色。鼠标处理程序应该做这样的事情。

void Script::OnLeftUp( wxMouseEvent& event )
{
    CallAfter(&Script::SelectCurWord);
    event.Skip();
}

我们必须使用 CallAfter 的原因是让事件处理在尝试添加选择之前完成其工作。 SelectCurWord 方法基本上是您之前使用的方法,但改为使用多项选择:

void Script::SelectCurWord()
{
    int currentPos = GetCurrentPos();
    int wordStartPos = WordStartPosition( currentPos, true );
    int wordEndPos=WordEndPosition(wordStartPos, true);

    AddSelection(wordStartPos,currentPos);
    AddSelection(currentPos,wordEndPos);
}