有人知道哪个属性设置禁用控件的文本颜色吗?我需要在禁用的TextBox
中显示一些文本,并将其颜色设置为黑色。
注意:请查看下面Cheetah的答案,因为它确定了一个前提条件才能使此解决方案工作。设置TextBox
的BackColor
。
我认为你真正想做的是启用TextBox
并将ReadOnly
属性设置为true
。
在禁用的TextBox
中更改文本的颜色有点棘手。我认为你可能必须子类化并重写OnPaint
事件。
ReadOnly
可以让你获得与!Enabled
相同的结果,并允许你控制TextBox
的颜色和格式。我认为它仍然支持从TextBox
选择和复制文本,而这在禁用的TextBox
中不可能。
另一个简单的替代方法是使用Label
而不是TextBox
。
此外,在标记为只读的文本框上遵守ForeColor,您必须明确设置BackColor。如果要仍然使用默认的BackColor,您必须进行显式设置,因为设计器在这里太聪明了。将BackColor设置为其当前值就足够了。我在窗体的Load事件中这样做:
private void FormFoo_Load(...) {
txtFoo.BackColor = txtFoo.BackColor;
}
我刚刚找到了一种很好的方法。在我的示例中,我使用了 RichTextBox,但是它应该适用于任何控件:
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);
}
}
您好,将 readonly 属性设置为 true 应该在代码或运行时而不是设计时进行。
txtFingerPrints.BackColor = System.Drawing.SystemColors.Info;
txtFingerPrints.ReadOnly = true;
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
}
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”事件中设置焦点
int index=this.Controls.IndexOf(this.textBox1);
this.Controls[index-1].Focus();
private void TextBoxName_EnabledChanged(System.Object sender, System.EventArgs e)
{
((TextBox)sender).ForeColor = Color.Black;
}
将“只读”设置为“True”是最简单的方法。
tabstop
属性设置为False,以防止默认选择文本。private void FormFoo_Load(...) {
txtFoo.Select(0, 0);
}
or
private void FormFoo_Load(...) {
txtFoo.SelectionLength = 0;
}