如何将WinForms文本框的前几个字符设置为只读?

时间:2022-09-11 17:00:43

I have a form with a textbox on it that is used to enter a URL. I need to add (http://) as a predefined value to this textbox and want it to be read only so the user won't be able to remove the http:// but he can write after it.

我有一个表单,上面有一个文本框,用于输入URL。我需要将(http://)作为预定义值添加到这个文本框中,并希望只读取它,这样用户就不能删除http://,但他可以在后面写。

如何将WinForms文本框的前几个字符设置为只读?

Any help would be highly appreciated.

如有任何帮助,我们将不胜感激。

10 个解决方案

#1


61  

Here are a few options:

以下是一些选择:

  1. The easy way is to just create a label outside the text box (to the left) with those characters. (simple and easy to understand for the user)

    简单的方法是在文本框外(左边)创建一个带有这些字符的标签。(简单易懂)

  2. Create a second readonly text box to use at the start, style it to match the input one and align them next to each other. Yes, you will get a single pixel line to split them both, but I think this will add to the user experience to make it obvious this is not for messing with (I would personally choose this option)

    创建第二个readonly文本框在开始时使用,样式化它以匹配输入框,并将它们彼此对齐。是的,你会得到一个单独的像素线来分割它们,但是我认为这将增加用户体验,使它很明显这不是为了干扰(我将亲自选择这个选项)

  3. If you need the style you can roll your own user control that uses a panel, label and textbox with appropriate border styling set as needed. (best way to get the exact style you need)

    如果您需要样式,您可以根据需要滚动自己的用户控件,该控件使用带有适当边框样式集的面板、标签和文本框。(获得所需风格的最佳方式)

  4. The fourth, more annoying way, would be to handle one of the key events (such as KeyDown) on the textbox itself. With this you can do numerous checks and alter the caret position to make it work, but trust me this will do your head in trying to get it working perfectly! (way too much hard work to get right)

    第四种更烦人的方式是处理文本框本身的一个关键事件(如KeyDown)。有了这个你可以做很多检查和改变插入符号的位置使它工作,但是相信我这将做你的头脑努力使它完美地工作!(做得太辛苦了)

To summarise, I think option 2 is the best here. Of course if you were using WPF you would undoubtedly have a lot more flexibility in styling.

总之,我认为第二种选择是最好的。当然,如果你使用WPF,你无疑会在造型上有更多的灵活性。

#2


20  

Have you considered placing a label beside it with "http://" as the text? and then when accepting the users input you can just append the "http://" with your textbox.Text.

你有没有考虑过在它旁边加上一个“http://”作为文本?然后在接受用户输入时,你可以将“http://”附加到你的文本框中。

Here is another idea:

这是另一个想法:

On every backspace press, count the number of characters in your textbox. If it is == 7, then ignore the backspace. If it is greater, then check the number of characters after the backspace. If the number of characters is less than 7, clear the textbox and reset the text.

在每次按下回车键时,数一下文本框中的字符数。如果是== 7,则忽略回退空间。如果它更大,那么在退格后检查字符数。如果字符数小于7,则清除文本框并重新设置文本。

private void a_keyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)8)
    {
        if (myTextbox.Text.Length == 7)
        // do stuff..
    }
    else if //do stuff...
}

#3


12  

You could also not even display the http:// and just append it to the Textbox.Text code. Check first that it doesn't start with that as well.

你甚至不能显示http://,而只是把它附加到文本框中。文本的代码。首先检查它是不是从那个开始。

To clarify my last remark:

澄清我的最后一句话:

string sURL = txtURL.Text.StartsWith("http://") ? txtURL.Text : "http://" + txtURL.Text;

#4


6  

Something like this?

是这样的吗?

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
    var textBox = sender as TextBox;

    if (!textBox.Text.StartsWith("http://"))
    {
        textBox.Text = "http://";
        textBox.Select(textBox.Text.Length, 0);

    }
}

#5


5  

You could use a RichTextBox instead, it allows protecting text:

你可以使用RichTextBox,它允许保护文本:

    public Form1() {
        InitializeComponent();
        richTextBox1.Text = "http://";
        richTextBox1.SelectAll();
        richTextBox1.SelectionProtected = true;
        richTextBox1.SelectionStart = richTextBox1.Text.Length;
        richTextBox1.DetectUrls = false;  // optional
    }

But unfortunately it doesn't work well if you set its Multiline property to False.

但不幸的是,如果将它的Multiline属性设置为False,它就不能正常工作。

A pragmatic way to do it with a TextBox is to just set it back the way you want it. Also works with pastes and selection deletes:

用文本框来实现这个功能的一个实用方法是将它设置为您想要的方式。也可以使用pastes和selection deletes:

    string protect = "http://";

    private void textBox1_TextChanged(object sender, EventArgs e) {
        if (!textBox1.Text.StartsWith(protect)) {
            textBox1.Text = protect;
            textBox1.SelectionStart = textBox1.Text.Length;
        }
    }

#6


4  

If you wanted a CSS approach (coupled with a background image) you can try something like this:

如果你想要CSS方法(结合背景图片),你可以尝试以下方法:

Enter URL: <input type="text" size="50" class="url" value="www.google.com" />

<style>
  input[type="text"].url {
    background: url(http://s18.postimage.org/4wkjdpidh/http.png) no-repeat left top transparent;
    text-indent: 34px;
  }
</style>

Then it's just a matter of prepending the http:// back on the input's value when you go to process it.

然后只需在输入的值上加上http://作为前缀就可以了。

#7


4  

Note: I misread the question, due to somehow I was coming here from the "HTML"-tag. But if you want to do something like this with HTML/CSS, this could be one solution.

注意:我误读了这个问题,因为我从“HTML”标签来到这里。但是如果你想用HTML/CSS做类似的事情,这可能是一个解决方案。

You could do something like this:

你可以这样做:

<style>
    label.mylabel, input.myinput {
        display:        block;
        float:          left;
        height:         20px;
        margin:         0;
        padding:        10px 5px 0px 5px;
        border:         1px solid #ccc;
        font-size:      11px;
        line-height:    11px;
    }

    label.mylabel {
        border-right:   0;
    }

    input.myinput {
        border-left:    0;
    }
</style>

<label class="mylabel" for="myinput">http://</label>
<input id="myinput" class="myinput" name="myinput" value="">

So this has two advantages:

所以这有两个优点

  • it looks like one input box
  • 它看起来像一个输入框
  • when the user hits "http", the actually form field will be focused
  • 当用户点击“http”时,实际的表单字段将被集中。

And of course, you have to add the 'http://' manually after sending in the form.

当然,在输入表单之后,您必须手动添加“http://”。

The whole thing has one disadvantage. What is, if your user wants to insert 'https://'? :)

整件事有一个缺点。如果您的用户想要插入“https://”,应该是什么?:)

Cheers, Philipp

欢呼,菲利普

#8


1  

You can put a label just left to the textboxt and set its text property to "http://". or you can append 2 textboxes one is read only the other is not read only. and write http:// in the one which is read only.

您可以在textboxt上留下一个标签,并将其文本属性设置为“http://”。或者你可以附加两个文本框一个是只读的另一个不是只读的。将http://写在只读的那个中。

#9


0  

Create a delegate for the keyup event (and possibly others, e.g. Clipboard) and check the start of the value.

为keyup事件(可能还有其他事件,例如剪贴板)创建一个委托,并检查值的开头。

#10


0  

$('#myField').bind('keypress', function(event)
{
    if (event.charCode == 0 && event.currentTarget.value.length <= 7)
{
     return false;
}
});

#1


61  

Here are a few options:

以下是一些选择:

  1. The easy way is to just create a label outside the text box (to the left) with those characters. (simple and easy to understand for the user)

    简单的方法是在文本框外(左边)创建一个带有这些字符的标签。(简单易懂)

  2. Create a second readonly text box to use at the start, style it to match the input one and align them next to each other. Yes, you will get a single pixel line to split them both, but I think this will add to the user experience to make it obvious this is not for messing with (I would personally choose this option)

    创建第二个readonly文本框在开始时使用,样式化它以匹配输入框,并将它们彼此对齐。是的,你会得到一个单独的像素线来分割它们,但是我认为这将增加用户体验,使它很明显这不是为了干扰(我将亲自选择这个选项)

  3. If you need the style you can roll your own user control that uses a panel, label and textbox with appropriate border styling set as needed. (best way to get the exact style you need)

    如果您需要样式,您可以根据需要滚动自己的用户控件,该控件使用带有适当边框样式集的面板、标签和文本框。(获得所需风格的最佳方式)

  4. The fourth, more annoying way, would be to handle one of the key events (such as KeyDown) on the textbox itself. With this you can do numerous checks and alter the caret position to make it work, but trust me this will do your head in trying to get it working perfectly! (way too much hard work to get right)

    第四种更烦人的方式是处理文本框本身的一个关键事件(如KeyDown)。有了这个你可以做很多检查和改变插入符号的位置使它工作,但是相信我这将做你的头脑努力使它完美地工作!(做得太辛苦了)

To summarise, I think option 2 is the best here. Of course if you were using WPF you would undoubtedly have a lot more flexibility in styling.

总之,我认为第二种选择是最好的。当然,如果你使用WPF,你无疑会在造型上有更多的灵活性。

#2


20  

Have you considered placing a label beside it with "http://" as the text? and then when accepting the users input you can just append the "http://" with your textbox.Text.

你有没有考虑过在它旁边加上一个“http://”作为文本?然后在接受用户输入时,你可以将“http://”附加到你的文本框中。

Here is another idea:

这是另一个想法:

On every backspace press, count the number of characters in your textbox. If it is == 7, then ignore the backspace. If it is greater, then check the number of characters after the backspace. If the number of characters is less than 7, clear the textbox and reset the text.

在每次按下回车键时,数一下文本框中的字符数。如果是== 7,则忽略回退空间。如果它更大,那么在退格后检查字符数。如果字符数小于7,则清除文本框并重新设置文本。

private void a_keyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)8)
    {
        if (myTextbox.Text.Length == 7)
        // do stuff..
    }
    else if //do stuff...
}

#3


12  

You could also not even display the http:// and just append it to the Textbox.Text code. Check first that it doesn't start with that as well.

你甚至不能显示http://,而只是把它附加到文本框中。文本的代码。首先检查它是不是从那个开始。

To clarify my last remark:

澄清我的最后一句话:

string sURL = txtURL.Text.StartsWith("http://") ? txtURL.Text : "http://" + txtURL.Text;

#4


6  

Something like this?

是这样的吗?

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
    var textBox = sender as TextBox;

    if (!textBox.Text.StartsWith("http://"))
    {
        textBox.Text = "http://";
        textBox.Select(textBox.Text.Length, 0);

    }
}

#5


5  

You could use a RichTextBox instead, it allows protecting text:

你可以使用RichTextBox,它允许保护文本:

    public Form1() {
        InitializeComponent();
        richTextBox1.Text = "http://";
        richTextBox1.SelectAll();
        richTextBox1.SelectionProtected = true;
        richTextBox1.SelectionStart = richTextBox1.Text.Length;
        richTextBox1.DetectUrls = false;  // optional
    }

But unfortunately it doesn't work well if you set its Multiline property to False.

但不幸的是,如果将它的Multiline属性设置为False,它就不能正常工作。

A pragmatic way to do it with a TextBox is to just set it back the way you want it. Also works with pastes and selection deletes:

用文本框来实现这个功能的一个实用方法是将它设置为您想要的方式。也可以使用pastes和selection deletes:

    string protect = "http://";

    private void textBox1_TextChanged(object sender, EventArgs e) {
        if (!textBox1.Text.StartsWith(protect)) {
            textBox1.Text = protect;
            textBox1.SelectionStart = textBox1.Text.Length;
        }
    }

#6


4  

If you wanted a CSS approach (coupled with a background image) you can try something like this:

如果你想要CSS方法(结合背景图片),你可以尝试以下方法:

Enter URL: <input type="text" size="50" class="url" value="www.google.com" />

<style>
  input[type="text"].url {
    background: url(http://s18.postimage.org/4wkjdpidh/http.png) no-repeat left top transparent;
    text-indent: 34px;
  }
</style>

Then it's just a matter of prepending the http:// back on the input's value when you go to process it.

然后只需在输入的值上加上http://作为前缀就可以了。

#7


4  

Note: I misread the question, due to somehow I was coming here from the "HTML"-tag. But if you want to do something like this with HTML/CSS, this could be one solution.

注意:我误读了这个问题,因为我从“HTML”标签来到这里。但是如果你想用HTML/CSS做类似的事情,这可能是一个解决方案。

You could do something like this:

你可以这样做:

<style>
    label.mylabel, input.myinput {
        display:        block;
        float:          left;
        height:         20px;
        margin:         0;
        padding:        10px 5px 0px 5px;
        border:         1px solid #ccc;
        font-size:      11px;
        line-height:    11px;
    }

    label.mylabel {
        border-right:   0;
    }

    input.myinput {
        border-left:    0;
    }
</style>

<label class="mylabel" for="myinput">http://</label>
<input id="myinput" class="myinput" name="myinput" value="">

So this has two advantages:

所以这有两个优点

  • it looks like one input box
  • 它看起来像一个输入框
  • when the user hits "http", the actually form field will be focused
  • 当用户点击“http”时,实际的表单字段将被集中。

And of course, you have to add the 'http://' manually after sending in the form.

当然,在输入表单之后,您必须手动添加“http://”。

The whole thing has one disadvantage. What is, if your user wants to insert 'https://'? :)

整件事有一个缺点。如果您的用户想要插入“https://”,应该是什么?:)

Cheers, Philipp

欢呼,菲利普

#8


1  

You can put a label just left to the textboxt and set its text property to "http://". or you can append 2 textboxes one is read only the other is not read only. and write http:// in the one which is read only.

您可以在textboxt上留下一个标签,并将其文本属性设置为“http://”。或者你可以附加两个文本框一个是只读的另一个不是只读的。将http://写在只读的那个中。

#9


0  

Create a delegate for the keyup event (and possibly others, e.g. Clipboard) and check the start of the value.

为keyup事件(可能还有其他事件,例如剪贴板)创建一个委托,并检查值的开头。

#10


0  

$('#myField').bind('keypress', function(event)
{
    if (event.charCode == 0 && event.currentTarget.value.length <= 7)
{
     return false;
}
});