如何更改禁用TextBox的字体颜色?

时间:2008-11-09 17:38:42

标签: c# winforms

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

9 个答案:

答案 0 :(得分:54)

注意:请参阅下面的Cheetah答案,因为它确定了使此解决方案有效的先决条件。设置BackColor的{​​{1}}。


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

更改已禁用true中文本的颜色有点棘手。我想你可能必须继承并覆盖TextBox事件。

OnPaint虽然可以提供与ReadOnly相同的结果,但可以让您保持对!Enabled的颜色和格式的控制。我认为它仍然支持从TextBox选择和复制文本,而禁用TextBox是不可能的。

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

答案 1 :(得分:53)

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

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

答案 2 :(得分:5)

喜 将readonly属性设置为代码端的true或运行时而不是设计时

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

答案 3 :(得分:4)

我刚刚找到了一个很好的方法。在我的示例中,我使用的是RichTextBox,但它应该适用于任何Control:

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,它会像标签一样,防止焦点,用户输入,光标变化,而不会被实际禁用。

看看它是否适合您。 问候

答案 4 :(得分:2)

你可以试试这个。 覆盖TextBox的OnPaint事件。

    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”

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
}

Refrence

或者你可以试试这个黑客

在Enter事件中设置焦点

int index=this.Controls.IndexOf(this.textBox1);

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

因此,您的控件不会聚焦,并且表现得像禁用一样。

答案 5 :(得分:1)

只需处理启用已更改并将其设置为您需要的颜色

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

答案 6 :(得分:0)

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

即可

答案 7 :(得分:0)

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

或者,您也可以这样做:

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

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

答案 8 :(得分:-1)

设置'只读' as' True'是最简单的方法。

相关问题