Binh Tran
Binh Tran

Reputation: 133

Identify where the cursor is in TextBox and change background color

I'm playing with a toy Text Editor. I want to mimic Notepad++ 's highlight current line (change the background color of the line where the cursor is).

How can I do that in C#?

Upvotes: 1

Views: 405

Answers (2)

jac
jac

Reputation: 9726

It can be done. I haven't worked it all out, but you need to create your own control inheriting from the TextBox control. You'll override the OnPaint event and draw your own background there. Here is enough to get you started.

public partial class MyTextBox : TextBox
{
    public MyTextBox()
    {
        InitializeComponent();
        // Need the following line to enable the OnPaint event
        SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        // this demonstrates the concept, but doesn't do what you want
        base.OnPaint(e);
        Point p = this.GetPositionFromCharIndex(this.SelectionStart);
        e.Graphics.FillRectangle(Brushes.Aqua, 0, p.Y, this.Width, (int)e.Graphics.MeasureString("A", this.Font).Height);
    }
}

Upvotes: 2

Deleted
Deleted

Reputation: 930

I don't think you can with a simple textbox, only with a RichTextBox. This link will get you started with some ideas for implementing a "highlight current line" -type UI.

Upvotes: 2

Related Questions