在用户将文本输入到 TextBox
之前显示“Type here to ...”是当今众所周知的可用性功能。如何在 C# 中实现这一功能?
我的想法是重写 OnTextChanged
,但是处理“在这里输入”文本变化的逻辑有点棘手...
在初始化时显示“在此输入”并在第一次输入时将其删除很容易,但我想在每次输入的文本变为空时显示消息。
最佳答案
对我有用的东西:
this.waterMarkActive = true;
this.textBox.ForeColor = Color.Gray;
this.textBox.Text = "Type here";
this.textBox.GotFocus += (source, e) =>
{
if (this.waterMarkActive)
{
this.waterMarkActive = false;
this.textBox.Text = "";
this.textBox.ForeColor = Color.Black;
}
};
this.textBox.LostFocus += (source, e) =>
{
if (!this.waterMarkActive && string.IsNullOrEmpty(this.textBox.Text))
{
this.waterMarkActive = true;
this.textBox.Text = "Type here";
this.textBox.ForeColor = Color.Gray;
}
};
其中bool waterMarkActive
是类成员变量,textBox
是TextBox
。虽然这可能应该被封装 :) 这种方法可能存在一些问题,但我目前还没有发现任何问题。
我最近发现 Windows 支持文本框中的水印;它们被称为提示横幅(参见 here )。它很容易实现:
// Within your class or scoped in a more appropriate location:
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
// In your constructor or somewhere more suitable:
SendMessage(textBox.Handle, 0x1501, 1, "Please type here.");
其中textBox
是TextBox
的实例,0x1501
是windows消息EM_SETCUEBANNER
的代码, wParam
可以是TRUE
(非零)或FALSE
(零),lParam
是水印你想展示。 wParam
指示何时应显示提示横幅;如果设置为 TRUE
,则即使控件具有焦点,也会显示提示横幅。
关于c# - 如何实现显示 "Type here"的 TextBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2487104/