[英]Identify where the cursor is in TextBox and change background color
我正在玩玩具文字編輯器。 我想模仿Notepad ++的高亮顯示當前行(更改光標所在行的背景顏色)。
我怎么能在C#中做到這一點?
我認為你不能使用簡單的文本框,只能使用RichTextBox。 此鏈接將為您提供實現“突出顯示當前行”類型UI的一些想法。
可以辦到。 我沒有全力以赴,但你需要創建自己的繼承自TextBox控件的控件。 您將覆蓋OnPaint事件並在那里繪制自己的背景。 這足以讓你入門。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.