如何向richTextBox添加新行
本文关键字:添加 新行 richTextBox | 更新日期: 2023-09-27 18:20:29
我有一个鼠标按下事件,我正在向richTextBox:写入文本
private void pictureBoxSnap_MouseDown(object sender, MouseEventArgs e)
{
richTextBox1.Text += "Rectangle Location: " + e.Location + Environment.NewLine;
Bitmap bmp;
Point pnt;
if (e.Button == MouseButtons.Right)
{
cm.Show(pictureBoxSnap, e.Location);
return;
}
if (e.Button == MouseButtons.Left)
{
if (checkError(listBox1.SelectedIndex, "pictureBoxSnap_MouseDown") == true) { return; } //if listBox1 empty
if (isCroppedList[listBox1.SelectedIndex] == true) { return; }
mouseDown = e.Location;
if (canDrawNormallyList[listBox1.SelectedIndex] == false)
{
bmp = new Bitmap(pictureBoxSnap.Width - 4, pictureBoxSnap.Height - 4);
pnt = PointToScreen(pictureBoxSnap.Location);
g = Graphics.FromImage(bmp);
g.CopyFromScreen(pnt.X + 2, pnt.Y + 2, 0, 0, new Size(bmp.Width, bmp.Height));
g.Dispose();
windowsBitmaps[listBox1.SelectedIndex] = bmp;
}
else
{
if (thumb != IntPtr.Zero)
{
MessageBoxButtons buttons = MessageBoxButtons.OK;
MessageBoxIcon icon = MessageBoxIcon.Error;
MessageBox.Show("ERROR in pictureBoxSnap_MouseDown: thumb != IntPtr.Zero", "ERROR", buttons, icon);
this.Close();
}
}
}
}
在鼠标按下事件中,我正在写矩形的位置。
然后在DrawRectangle方法中,我想在richTextBox1中实时显示矩形的大小:
private void DrawRectangle(Point pnt)
{
g = Graphics.FromImage(img);
g.Clear(Color.FromKnownColor(KnownColor.Control));
if (pnt.X == mouseDown.X || pnt.Y == mouseDown.Y)
{
g.DrawLine(Pens.Firebrick, mouseDown.X, mouseDown.Y, pnt.X, pnt.Y);
}
else
{
g.DrawRectangle(Pens.Firebrick, Math.Min(mouseDown.X, pnt.X), Math.Min(mouseDown.Y, pnt.Y),
Math.Abs(mouseDown.X - pnt.X), Math.Abs(mouseDown.Y - pnt.Y));
richTextBox1.Text = "Rectangle Size: " + Math.Abs(mouseDown.X - pnt.X) +
Math.Abs(mouseDown.Y - pnt.Y);
}
g.Dispose();
g = frm.CreateGraphics();
g.DrawImage(img, 0, 0, img.Width, img.Height);
g.Dispose();
}
现在的问题是,当我用鼠标左键点击鼠标时,我看到了位置,但当我移动鼠标时,拖动位置线时,位置线被删除,我看到的是尺寸线。如果在DrawRectangle方法中,我也使+=它只是多次添加尺寸线,当我移动/拖动鼠标时,用它填充整个richTextBox。
每次都需要追加。您当前正在做的是覆盖已经存在的文本。
此:
richTextBox1.Text = "Rectangle Location: " + e.Location + Environment.NewLine;
说:"richtextbox文本的值必须是我提供的
然而:
richTextBox1.Text += "Rectangle Location: " + e.Location + Environment.NewLine;
// ^^^^ append
说:"richtextbox文本必须是当前的……加上这些额外的东西。"
有一个标志变量。
int flag=0;
if(flag==0)
{
richTextBox1.Text += "Rectangle Location: " + e.Location;
flag++;
}
else
{
richTextBox1.Text += Environment.NewLine + "Rectangle Location: " + e.Location + ;
}
首先,我想给你一些建议。当使用if语句时,当您可以使用if(isCroppedList[listBox1.SelectedIndex])。解决您问题的解决方案可能是:检查Multiline是否设置为True,或者尝试richTextBox.AppendText(txt).