Cod*_*ray 17
看起来您正在描述一个提示横幅,这是一个显示在空文本框中的提示文本.从Windows XP开始,操作系统本身支持此功能.以这种方式实现的效果比在TextChanged事件中自己设置默认文本更加优雅.它看起来像这样:

通过向文本框控件发送EM_SETCUEBANNER消息,可以在Windows API级别完成此设置.要从.NET项目中使用它,您必须使用P/Invoke.
幸运的是,大部分工作已经为您完成.此示例项目是一种快速,轻松的方式,可以将cue banner支持添加到现有项目中.这是另一个示例,其中包含对该过程的更完整说明.
如果您不希望应用程序依赖外部DLL,则可以将必要的代码直接添加到项目中.最简单的方法是对现有TextBox控件进行子类化,并添加代码以支持那里的提示横幅.请参阅此答案以获取您需要的代码.如果您将其转换为VB.NET时遇到问题,请尝试使用此工具.
TextChanged如果事件触发时文本框为空,您可能需要处理该事件并设置一些默认文本。
我没有 VB.NET 示例,但是下面的 C# 应该太难理解了:
public Form1()
{
this.InitializeComponent();
textBox1.Tag = "Default text";
textBox1.Text = (string)textBox1.Tag;
textBox1.TextChanged += new EventHandler(OnTextChanged);
}
void OnTextChanged(object sender, EventArgs e)
{
var textbox = (TextBox)sender;
if (string.IsNullOrEmpty(textbox.Text))
{
textbox.Text = (string)textbox.Tag;
}
}
Run Code Online (Sandbox Code Playgroud)
并且事件处理程序可以重复用于多个文本框。
编辑:这在 VB.NET 中几乎相同
Sub New()
' This call is required by the designer.
InitializeComponent()
TextBox1.Tag = "Default text" ' This can be set with the designer
TextBox1.Text = CStr(TextBox1.Tag)
End Sub
Private Sub OnTextBoxTextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim textbox As TextBox = DirectCast(sender, TextBox)
If String.IsNullOrEmpty(textbox.Text) Then
textbox.Text = CStr(textbox.Tag)
textbox.SelectAll()
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
当然,您也可以使用本机 Windows 功能实现类似的行为,但即使您不想使用 Win32,几行托管代码也能满足您几乎所需的一切。
| 归档时间: |
|
| 查看次数: |
48553 次 |
| 最近记录: |