关于c#:如何更改禁用的TextBox的字体颜色?

How to change the font color of a disabled TextBox?

有人知道哪个属性设置了禁用控件的文本颜色吗?
我必须在禁用的TextBox中显示一些文本,并且要将其颜色设置为黑色。


注意:请参阅下面的猎豹的答案,因为它确定了使此解决方案生效的先决条件。设置TextBox

BackColor

我认为您真正想做的是启用TextBox并将ReadOnly属性设置为true

在禁用的TextBox中更改文本的颜色有点棘手。我认为您可能必须继承并覆盖OnPaint事件。

尽管

ReadOnly应该会为您提供与!Enabled相同的结果,并允许您保持对TextBox的颜色和格式的控制。我认为它还将仍然支持从TextBox选择和复制文本,而禁用TextBox则无法实现。

另一个简单的替代方法是使用Label代替TextBox


此外,为了使ForeColor在标记为ReadOnly的TextBox上服从,必须显式设置BackColor。如果您希望它仍然使用默认的BackColor,则必须使该设置显式,因为设计师在这里本身就太聪明了。将BackColor设置为其当前值就足够了。我在表单的Load事件中执行此操作,如下所示:

1
2
3
private void FormFoo_Load(...) {
    txtFoo.BackColor = txtFoo.BackColor;
}


我刚刚找到了一种很棒的方法。在我的示例中,我使用的是RichTextBox,但它应可与任何Control:

一起使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class DisabledRichTextBox : System.Windows.Forms.RichTextBox
{
    // See: http://wiki.winehq.org/List_Of_Windows_Messages

    private const int WM_SETFOCUS   = 0x07;
    private const int WM_ENABLE     = 0x0A;
    private const int WM_SETCURSOR  = 0x20;

    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        if (!(m.Msg == WM_SETFOCUS || m.Msg == WM_ENABLE || m.Msg == WM_SETCURSOR))
            base.WndProc(ref m);
    }
}

您可以安全地设置Enabled = true和ReadOnly = false,它将像标签一样,防止焦点,用户输入,光标更改,而没有被实际禁用。

查看它是否对您有用。
问候


hi
从代码方面或运行时而不是从设计时

将readonly属性设置为true

1
2
txtFingerPrints.BackColor = System.Drawing.SystemColors.Info;
txtFingerPrints.ReadOnly = true;

您可以尝试一下。
重写TextBox的OnPaint事件。

1
2
3
4
5
6
    protected override void OnPaint(PaintEventArgs e)
{
     SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property
     // Draw string to screen.
     e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f); //Use the Font property
}

将ControlStyles设置为" UserPaint "

1
2
3
4
5
6
7
8
9
public MyTextBox()//constructor
{
     // This call is required by the Windows.Forms Form Designer.
     this.SetStyle(ControlStyles.UserPaint,true);

     InitializeComponent();

     // TODO: Add any initialization after the InitForm call
}

参考

或者您可以尝试此技巧

在Enter事件中设置焦点

1
2
3
int index=this.Controls.IndexOf(this.textBox1);

this.Controls[index-1].Focus();

因此您的控件将不会聚焦并且表现为禁用状态。


只需更改启用句柄,然后将其设置为所需的颜色

1
2
3
4
private void TextBoxName_EnabledChanged(System.Object sender, System.EventArgs e)
{
    ((TextBox)sender).ForeColor = Color.Black;
}


除了@ spoon16和@Cheetah的答案外,我总是在文本框上将tabstop属性设置为False,以防止默认情况下选择文本。

或者,您也可以执行以下操作:

1
2
3
private void FormFoo_Load(...) {
    txtFoo.Select(0, 0);
}

1
2
3
private void FormFoo_Load(...) {
    txtFoo.SelectionLength = 0;
}


将\\'只读\\'设置为\\'真\\'是最简单的方法。


如果要显示无法编辑或选择的文本,只需使用标签