【问题标题】:Change selected Text BackColor in TextBox更改文本框中选定的文本背景颜色
【发布时间】:2011-08-10 10:45:08
【问题描述】:

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

谢谢,

汤姆

【问题讨论】:

    标签: .net winforms textbox


    【解决方案1】:

    也许这会有所帮助...

    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);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 2013-01-15
      • 2013-05-20
      • 2013-08-03
      相关资源
      最近更新 更多