我正在使用Winform作为工具进行邮件合并。我提供了2个模板,一个用于商业信函,另一个用于备忘录。对于字母,用户通常键入字母的正文,而其他信息是从用户通过单击“选择收件人”选项创建的数据文件中选取的。
我想限制我的用户只输入正文,指针必须位于第二行称呼之后。指针不能从该位置向后移动,但当然可以向前移动。我该怎么做?
如果我不清楚,我很抱歉。
答案 0 :(得分:0)
如果您的文字位于TextBox
或RichTextBox
,则可以选择控件并将光标置于
// Set the cursor into the text box
bodyTextBox.Focus();
// Place the cursor at the desired position in the text
bodyTextBox.Select(start, 0);
您必须弄清楚第三行的开始位置
const int indent = 30; // Desired indentation
// Place focus in this control
bodyTextBox.Focus();
// The following work only if we have at least 3 lines of text
if (bodyTextBox.Lines.Length >= 3) {
int start = bodyTextBox.Lines[0].Length + // Length of first line
bodyTextBox.Lines[1].Length + // Length of second line
4 + // 2 x 2 characters for two CR-LFs
Math.Min(indent, bodyTextBox.Lines[2].Length);
bodyTextBox.Select(start, 0);
}
我认为文本看起来像这样
First line of text.<CR><LF> Second line of text.<CR><LF> <30 spaces for indent> ^ desired position
为了将光标设置在正确的位置,我们需要计算文本开头的字符总数。由于您希望将光标定位在第三行,这是两条第一行的长度加上两端的CR-LF(换行符)加上第三行开头的30个字符。如果第三行长度少于30个字符,我们无法将光标放在那里,因此我们将它放在尽可能远的地方,即Math.Min(indent, bodyTextBox.Lines[2].Length);
最后我们将光标放在Select
处。由于我们不想选择文本,因此我们将选择的长度定义为零。