.net - 在TextBox中更改选定的Text BackColor

标签 .net winforms textbox

我想知道如何为TextBox中的选定文本实现自定义背景色。默认情况下,它对所选文本使用Windows的标准颜色(浅蓝色)。由于我使用的是基于winforms TextBox的皮肤文本编辑器,而TextBox没有公开任何属性来更改颜色,因此我想知道是否还有其他方法可以在应用程序级别更改此系统默认颜色?

谢谢,

汤姆

最佳答案

也许这有帮助...

public class MyTextBox : System.Windows.Forms.TextBox
    {
        private const int WM_PAINT = 0x000F;

        public MyTextBox()
        {
            this.TextChanged += new System.EventHandler(this.myTextBox_TextChanged);

        }

        private void myTextBox_TextChanged(object sender, System.EventArgs e)
        {
        }


        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]    
        protected override void WndProc(ref Message m) 
        {
            base.WndProc(ref m);    
            // Listen for operating system messages.
            switch (m.Msg)
            {
                case WM_PAINT:
                    PaintEventArgs pe = new PaintEventArgs(this.CreateGraphics(),this.RectangleToScreen(this.ClientRectangle));
                    this.OnPaint(pe);
                    break;
            }

        }

        protected override void OnPaint(PaintEventArgs pe)
        {
    // call base.OnPaint(pe);
            Graphics g = pe.Graphics;
            g.Clear(this.BackColor);
            string s = this.Text.Substring(0,this.Text.Length/2);
   // provide a object with how to split your string with colors
            string s1 =  this.Text.Substring(this.Text.Length/2);
            SizeF sf = g.MeasureString(s,this.Font);
            g.DrawString(s,this.Font,new SolidBrush(Color.Red),0,0);

            g.DrawString(s1,this.Font,new SolidBrush(Color.Black),sf.Width,0);
        }
    }

关于.net - 在TextBox中更改选定的Text BackColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5746804/

相关文章:

c# - 在 C# 中搜索优先级队列(最小堆或最大堆),什么是有效结构?

c# - EventLog.EntryWritten 事件处理过去的事件

javascript - 如何用javascript对多个(未定义的数字)文本框的数字求和?

c# - 在 WPF 中单击按钮后如何清除文本框?

jquery - 是否有任何插件可以将文本框列表链接到选择下拉列表并使它们保持同步

c# - 如何将名字大写

.net - 有选择地从 LINQ 表达式树中的 where 子句中删除

c# - 如何在 C# 中使用鼠标选择 PictureBox.Image 上的区域

c# - 如何在 datagridviewcell 上绘制自定义控件?

C# 任何人都明白为什么这不能正确选择 datagridview 中的行