如何设置一个WinForms TextBox的前几个字符为只读? [英] How to set the first few characters of a WinForms TextBox to Read-Only?

查看:121
本文介绍了如何设置一个WinForms TextBox的前几个字符为只读?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有上有一个文本框用于输入URL的形式。我需要添加(HTTP://)作为一个预定值这个文本框,并希望它是只读的,因此用户无法删除HTTP://但是他之后写。

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.

任何帮助将高度赞赏

推荐答案

下面是几个选项:


  1. 最简单的办法是只创建的以这些字符的文本框(左侧)外标签。 (简单和容易理解的用户)

  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)

创建第二个只读文本框在开始使用,作风它来匹配输入之一,它们对齐彼此相邻。是的,你会得到一个单一的像素线,以他们两人分开,但我认为这将增加用户体验,使它明显这不是搞乱(我会亲自选择此选项)

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)

如果您需要的款式,你可以的推出自己的用户控件使用面板,标签和文本框以根据需要设置适当的边框样式。 (最好的方式得到你所需要的确切风格)

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)

第四,更恼人的方式,将是处理的关键事件之一(如<一个HREF =htt​​p://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown.aspx>的KeyDown )的文本本身。有了这个,你可以做许多检查和改变插入符位置,使其工作,但相信我,这将是在试图让它完美的工作做你的头! (太多的辛勤工作得到正确的)

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)

要总结,我觉得选项2 是这里最好的。当然,如果你使用WPF,你无疑会在造型更多的灵活性。

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.

这篇关于如何设置一个WinForms TextBox的前几个字符为只读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆