在VS C#中定义Tab和Enter,使其像在Python 3.7.x中一样工作



对于我的项目,我正在尝试在VS中"制作"一个python。我已经制作了正则表达式来突出显示语法,现在我需要使 Tab、Enter 和 Shift+Tab 像在 python 中一样工作。

我将其作为 WPF 中的测试,其中包含带有示例文本的文本框。我已经将工作输入作为新行和选项卡进行工作。

public MainWindow()
    {
        InitializeComponent();
        textBox.AcceptsTab = true;
    }
    private void OnKeyDownHandler(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            textBox.AppendText(Environment.NewLine);
        }
        if (e.Key == Key.Tab && e.Key == Key.LeftShift)
        {
        }
    }

现在我试图制作:

1.转移+标签删除标签。

2.当我标记几行并按 Tab/Shift+Tab 时,它将适用于所有行

3.当我按回车键时,它会将行与之前的行对齐。例如:

如果之前的一行有一个制表符,当我按下输入新行时也会有一个制表符。

我会很高兴得到任何提示。

好的,看起来你的textbox被命名为textBox所以我将使用它,并从你发布的代码开始。

以下内容似乎回答了您的问题,但它是我的头顶,因此在使用它之前请仔细阅读它。 我希望它能帮助您入门。

编辑:我刚刚注意到您的问题中涉及突出显示多行的部分。 这不在我下面编写的代码中,但可以通过使用 .SelectionStart.SelectionLength 来完成,确定哪些行受到影响,然后确定这些行是否有制表符等......

public MainWindow()
{
    InitializeComponent();
    textBox.AcceptsTab = true;
}
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        // append newline AND maybe some tabs
        textBox.AppendText(DoEnterPressed());
    }
    if (e.Key == Key.Tab && e.Key == Key.LeftShift)
    {
        // check, see and do
        DoShiftTab();
    }
}
//now we need those methods of course
private string DoEnterPressed()
{
    string ret = Environment.NewLine;
    //check how many tabs the line has...
    //I want the line we are on, not maybe the last line    
    string currentLine = textBox.GetLineText(textBox.GetLineIndexFromCharacterIndex(textBox.SelectionStart) );
    //  Only counting the tab chars at the start of string makes it easier
    int tabCnt = 0;
    foreach(char c in currentLine)
    {
        if(c == 't')
        {
            tabCnt++;
        }
        else
        {
            break;
        }
    }
    // now put the tabs in the return string after the newline
    for(int i = 0; i < tabCnt; i++)
    {
        ret += "t";
    }
    return ret;
}
private void DoShiftTab()
{
    //  let's see if the char before the cursor is tab, if so, remove it
    if(textBox.text[textBox.SelectionStart-1] == 't')
    {
        textBox.text.RemoveAt(textBox.SelectionStart-1);
    }
}

最新更新