简体   繁体   English

C# 中的只读文本框

[英]Read-only textbox in C#

In C# , I am creating a form window for a LAN messenger with two textboxes.C#中,我正在为带有两个文本框的 LAN Messenger 创建一个表单 window。 I need to create a particular textbox as read-only, but any text submitted to it is appearing grey which is not desirable.我需要创建一个只读的特定文本框,但提交给它的任何文本都显示为灰色,这是不可取的。 Is there any way that can be prevented?有什么方法可以预防吗?

I would use a Textbox and set ReadOnly to true, ForeColor to Color.Black, and BackColor to Color.White.我会使用文本框并将 ReadOnly 设置为 true,将 ForeColor 设置为 Color.Black,并将 BackColor 设置为 Color.White。 This way you can still select the text and copy it with Ctrl-C.这样你仍然可以 select 文本并使用 Ctrl-C 复制它。

You could replace it with a label or on the text box in the KeyPress event, set handled to true:您可以将其替换为 label 或 KeyPress 事件中的文本框,设置为 true:

void  textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = true;
}

You can set the colour of the text by setting the Textbox ForeColor property.您可以通过设置Textbox ForeColor属性来设置文本的颜色。

For example:例如:

myTextBox.ForeColor = Color.Black myTextBox.ForeColor = 颜色.黑色

In order to keep the textbox white (or Window) when it's read-only, you must explicitly set the BackColor property to Window.为了使文本框在只读状态下保持白色(或窗口),您必须将 BackColor 属性显式设置为 Window。 To do this, you must first set the BackColor to some other value, then back to Window.为此,您必须先将 BackColor 设置为其他值,然后再设置回 Window。 The backcolor property should become bold indicating it is no longer the default value. backcolor 属性应该变为粗体,表明它不再是默认值。

The grey color is indicative of the ReadOnly state of the textbox.灰色表示文本框的 ReadOnly state。 It is a visual indication to the user who will not need to enter text to discover that the textbox is in fact, disabled.它是对不需要输入文本即可发现文本框实际上已禁用的用户的视觉指示。

If you need only the readonly behaviour, you would be better off using a Label instead.如果您只需要只读行为,最好使用 Label 代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM