C#中的只读文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/589273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:23:09  来源:igfitidea点击:

Read-only textbox in C#

c#textbox

提问by Avik

In C#, I am creating a form window for a LAN messenger with two textboxes. 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?

C# 中,我正在为带有两个文本框的 LAN 信使创建一个表单窗口。我需要创建一个特定的文本框作为只读,但提交给它的任何文本都显示为灰色,这是不可取的。有什么办法可以预防吗?

回答by Cerebrus

The grey color is indicative of the ReadOnly state of the textbox. 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 代替。

回答by benPearce

You could replace it with a label or on the text box in the KeyPress event, set handled to true:

您可以将其替换为标签或 KeyPress 事件中的文本框,将其设置为 true:

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

回答by Michael Logothetis

You can set the colour of the text by setting the TextboxForeColorproperty.

您可以通过设置Textbox ForeColor属性来设置文本的颜色

For example:

例如:

myTextBox.ForeColor = Color.Black

myTextBox.ForeColor = Color.Black

回答by Oran Dennison

I would use a Textbox and set ReadOnly to true, ForeColor to Color.Black, and BackColor to Color.White. This way you can still select the text and copy it with Ctrl-C.

我会使用文本框并将 ReadOnly 设置为 true,将 ForeColor 设置为 Color.Black,将 BackColor 设置为 Color.White。这样您仍然可以选择文本并使用 Ctrl-C 复制它。

回答by Oran Dennison

In order to keep the textbox white (or Window) when it's read-only, you must explicitly set the BackColor property to Window. To do this, you must first set the BackColor to some other value, then back to Window. The backcolor property should become bold indicating it is no longer the default value.

为了在只读时保持文本框为白色(或 Window),您必须将 BackColor 属性显式设置为 Window。为此,您必须首先将 BackColor 设置为某个其他值,然后再设置回 Window。backcolor 属性应该变成粗体,表示它不再是默认值。