1

So I need to make a text editor in C# Forms using only drawString, drawLine etc.

As I type my text changes and that results in my text cursor not displaying properly because it depends on text width that I calculate through MeasureString().

Here is my function for writing text and drawing cursor:

private void TextEditor_Paint(object sender, PaintEventArgs e)
{
    pen = new Pen(Color.Black, 1);

    font = new System.Drawing.Font("Arial", teModel.font, System.Drawing.FontStyle.Regular, 
    System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));

    Graphics g = e.Graphics;

    string stringToMeasure = "";

    int i = 0;

    foreach (string line in teModel.allLines())
        g.DrawString(line, font, Brushes.Black, 0, teModel.font * i + teModel.lineGap * 
              i++,StringFormat.GenericTypographic);

    //Drawing cursor
    stringToMeasure ="";

    foreach (string str in teModel.linesRange(cursor.line, cursor.line + 1))
        stringToMeasure = str;

    float width = g.MeasureString(stringToMeasure.Substring(0, cursor.pos).Replace(' ', ','), 
           font,0,StringFormat.GenericTypographic).Width;

    g.DrawLine(teModel.isTextSelected()?whitePen:pen, width, 
    cursor.line*teModel.font+cursor.line*teModel.lineGap , width, cursor.line * teModel.font + 
           cursor.line * teModel.lineGap + teModel.font + teModel.lineGap * 2);

}

And here is the video of the problem

WSC
  • 903
  • 10
  • 30

0 Answers0