如何写但插入符号保持其位置? [英] How to write something but caret maintain its position?

查看:80
本文介绍了如何写但插入符号保持其位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个事件,该事件在其中执行一些计算("for"的)
经过这些计算之后,textBox1(对于我写的每个字母)中的插入符号将重定向到文本的开始,这就是为什么我在提供的代码中插入了最后一行,以纠正该错误: textBox1.SelectionStart = textBox1.Text.Length;
[我知道"SelectionStart"实际上是插入符号的位置,但是由于计算的原因,它是按照我的解释开始的]
现在我的问题是:当我想在文本内部插入一个新文本时,对于我写的每个字母,插入号都转到文本的末尾(因为提到了最后一行).如何书写但插入符号保持其位置?
谢谢.
这是代码:

I have this event which perform some computations inside it (the "for" ones)
The caret inside textBox1(for each letter I write), is redirected to the beginning of text after those computations, and thats why I inserted the last line in code provided, to rectify that bug: textBox1.SelectionStart = textBox1.Text.Length;
[I know that "SelectionStart" is in fact the caret position, but because of the computation, it start as I explained]
Now my problem is: When I want to insert a NEW text in the interior of the text, for each letter I write, the caret goes to the end of the text(because of the last line mentioned). How to write something but caret maintain its position?
Thanks.
Here is the code:

//Here are 4 arrays with chars.
     private void textBox1_TextChanged(object sender, EventArgs e) 
     {
            for (int i = 0; i < literaRom.Length; i++)
            {
                if (textBox1.Text.Contains(literaRom[i]))//lower
                    textBox1.Text = textBox1.Text.Replace(literaRom[i], literaRus[i]);
                if (textBox1.Text.Contains(literaRom[i].ToUpper()))//upper
                    textBox1.Text = textBox1.Text.Replace(literaRom[i].ToUpper(), literaRus[i].ToUpper());
            }

            for (int i = 0; i < literaKeyComp.Length; i++)
            {
                if (textBox1.Text.Contains(literaKeyComp[i]))//lower
                    textBox1.Text = textBox1.Text.Replace(literaKeyComp[i], literaRusComp[i]);
                if (textBox1.Text.Contains(literaKeyComp[i].ToUpper()))//upper
                    textBox1.Text = textBox1.Text.Replace(literaKeyComp[i].ToUpper(), literaRusComp[i].ToUpper());
            }


             textBox1.SelectionStart = textBox1.Text.Length;//redirected cursor (put carret at end of text)
     }

推荐答案

在执行操作之前,请先阅读SelectionStart,然后将其还原到末尾而不是将其设置为长度.您可能想检查一下所做的更改是否没有缩短文本的长度,或未将其插入插入符号之前-在这种情况下,您需要计算新的插入符号位置以保持其与用户文本的关系.
Read the SelectionStart before you do the operation, and restore it at the end instead of setting it to the length. You may want to check that your changes have not reduced the length of the text, or inserted before the caret - in which case you need to calculate the new caret position to maintain it''s relationship with the user text.


这篇关于如何写但插入符号保持其位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆