Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 确定光标在文本框中的位置并更改背景色_C#_Winforms - Fatal编程技术网

C# 确定光标在文本框中的位置并更改背景色

C# 确定光标在文本框中的位置并更改背景色,c#,winforms,C#,Winforms,我在玩一个玩具文本编辑器。我想模拟Notepad++高亮显示当前行(更改光标所在行的背景色) 我怎样才能在C#中做到这一点?我认为你不能用一个简单的文本框,只能用一个RichTextBox。我将为您介绍一些实现“突出显示当前行”类型用户界面的想法。我认为您不能使用简单的文本框,只能使用RichTextBox。将为您提供一些实现“突出显示当前行”类型UI的想法。这是可以做到的。我还没有完全解决这个问题,但是您需要创建自己的控件来继承TextBox控件。您将覆盖OnPaint事件并在那里绘制自己的背

我在玩一个玩具文本编辑器。我想模拟Notepad++高亮显示当前行(更改光标所在行的背景色)


我怎样才能在C#中做到这一点?

我认为你不能用一个简单的文本框,只能用一个RichTextBox。我将为您介绍一些实现“突出显示当前行”类型用户界面的想法。

我认为您不能使用简单的文本框,只能使用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);
    }
}

这是可以做到的。我还没有完全解决这个问题,但是您需要创建自己的控件来继承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);
    }
}