简体   繁体   English

光标位置不会在根处停止:winforms RichTextBox

[英]Cursor position does not stop at root: winforms RichTextBox

I am trying to implement a command line utility with RichTextBox in user interface. 我正在尝试在用户界面中使用RichTextBox实现命令行实用程序。 I am trying to restrict the usage of Left and Right arrow keys similar to MS Dos command prompt window. 我试图限制类似于MS Dos命令提示符窗口的Left and Right arrow keys的使用。 My implementation should not allow user to cross the current root. 我的实现不应允许用户跨越当前根目录。

eg

If C:\\Test> is root, user should not be allowed to cross '>' with left arrow key. 如果C:\\Test>是root用户,则不应允许用户使用左箭头键跨过'>'

Below is my code: 下面是我的代码:

richTextbox1.KeyDown += OnKeyDown;
string root = "C:\Test>";

void OnKeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Left:
        case Keys.Right:
        {
            int lastline = richTextbox1.Lines.Length - 1;
            int first = richTextbox1.GetFirstCharIndexFromLine(lastline);
            int valid = first + root.Length + 1;

            if (richTextbox1.SelectionStart < valid )
            {
                richTextbox1.Select(valid, 0);
                richTextbox1.Invalidate();
            }
        }
        break;
    }
}

It works for case: C:\\Test>xyz : when user keeps pressing left arrow , s/he can not go beyond > character 它适用于以下情况: C:\\Test>xyz :当用户持续按left arrow ,他/他不能超出>字符

Failing case: C:\\Test> : when user keeps pressing left arrow , s/he can go beyond > character and it stops at t 失败的情况: C:\\Test> :当用户持续按left arrow ,他/他可以超出>字符,并且在t停止

What is wrong with my code, I am not able to figure out? 我的代码有什么问题,我无法弄清楚?

Excellent, it works with e.Handled = true , working code as below: richTextbox1.KeyDown += OnKeyDown; e.Handled = true ,它与e.Handled = true一起工作,工作代码如下:richTextbox1.KeyDown + = OnKeyDown; string root = "C:\\Test>"; 字符串根=“ C:\\ Test>”;

void OnKeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Left:
        case Keys.Right:
        {
            int lastline = richTextbox1.Lines.Length - 1;
            int first = richTextbox1.GetFirstCharIndexFromLine(lastline);
            int valid = first + root.Length + 1;

            if (richTextbox1.SelectionStart < valid )
            {
                //richTextbox1.Select(valid, 0);
                //richTextbox1.Invalidate();
                e.Handled = true;
            }
        }
        break;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM