Watermark in System.Windows.Forms.Textbox

Watermark for Textbox

just tried this out. It seems to work fine in a new Windows Forms project.

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.ForeColor = SystemColors.GrayText;
textBox1.Text = "Please Enter Your Name";
this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave);
this.textBox1.Enter += new System.EventHandler(this.textBox1_Enter);
}

private void textBox1_Leave(object sender, EventArgs e)
{
if (textBox1.Text.Length == 0)
{
textBox1.Text = "Please Enter Your Name";
textBox1.ForeColor = SystemColors.GrayText;
}
}

private void textBox1_Enter(object sender, EventArgs e)
{
if (textBox1.Text == "Please Enter Your Name")
{
textBox1.Text = "";
textBox1.ForeColor = SystemColors.WindowText;
}
}
}

Watermark in System.Windows.Forms.TextBox

lately I needed a watermark textbox, the first thing that popped in to my head was OnLeave and OnEnter events of textbox, but first I googled it and I got two links first was the one in CodeProject which used the System.Drawing namespace and the other one was here using the SendMessage() over here http://vidmar.net/weblog/archive/2008/11/05/watermarked-textbox-in-windows-forms-on-.net.aspx.

I beleive the SendMessage one is much easier and it also has no flickering in it. though I used it.

I hope it will be helpful for you.

Watermark TextBox in WinForms

The official term is "cue banner". Here's another way to do it, just inheriting TextBox gets the job done too. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox and set the Cue property.

You get a live preview of the Cue value in the designer, localized to the form's Language property. Lots of bang for very little buck, an excellent demonstration of the good parts of Winforms.

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class CueTextBox : TextBox {
[Localizable(true)]
public string Cue {
get { return mCue; }
set { mCue = value; updateCue(); }
}

private void updateCue() {
if (this.IsHandleCreated && mCue != null) {
SendMessage(this.Handle, 0x1501, (IntPtr)1, mCue);
}
}
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
updateCue();
}
private string mCue;

// PInvoke
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, string lp);
}

Creating a TextBox with watermark using ControlStyles.UserPaint shows the watermark just once at component creation

Edit: Resurrected due to OP giving up on custom fore color requirement.

This feature is supported by the native edit control that the WinForm Textbox class wraps. It is supported in Windows Vista and greater if visual styles are enabled.

reference: EM_SETCUEBANNER message

Example:

Imports System.Runtime.InteropServices

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SetWaterMark(TextBox1, "Enter Something Here", True)
End Sub

<DllImport("user32.dll", CharSet:=CharSet.Unicode)>
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As Boolean, ByVal lParam As String) As Boolean
End Function

Private Shared Sub SetWaterMark(tb As TextBox, waterMarkText As String, Optional showIfFocused As Boolean = True)
Const ECM_FIRST As Int32 = &H1500
Const EM_SETCUEBANNER As Int32 = ECM_FIRST + 1
If VisualStyles.VisualStyleInformation.IsEnabledByUser Then
SendMessage(tb.Handle, EM_SETCUEBANNER, showIfFocused, waterMarkText)
End If
End Sub
End Class

Watermark / hint / placeholder text in TextBox?

This is a sample which demonstrates how to create a watermark textbox in WPF:

<Window x:Class="WaterMarkTextBoxDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WaterMarkTextBoxDemo"
Height="200" Width="400">

<Window.Resources>

<SolidColorBrush x:Key="brushWatermarkBackground" Color="White" />
<SolidColorBrush x:Key="brushWatermarkForeground" Color="LightSteelBlue" />
<SolidColorBrush x:Key="brushWatermarkBorder" Color="Indigo" />

<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<local:TextInputToVisibilityConverter x:Key="TextInputToVisibilityConverter" />

<Style x:Key="EntryFieldStyle" TargetType="Grid" >
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Margin" Value="20,0" />
</Style>

</Window.Resources>

<Grid Background="LightBlue">

<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>

<Grid Grid.Row="0" Background="{StaticResource brushWatermarkBackground}" Style="{StaticResource EntryFieldStyle}" >
<TextBlock Margin="5,2" Text="This prompt dissappears as you type..." Foreground="{StaticResource brushWatermarkForeground}"
Visibility="{Binding ElementName=txtUserEntry, Path=Text.IsEmpty, Converter={StaticResource BooleanToVisibilityConverter}}" />
<TextBox Name="txtUserEntry" Background="Transparent" BorderBrush="{StaticResource brushWatermarkBorder}" />
</Grid>

<Grid Grid.Row="1" Background="{StaticResource brushWatermarkBackground}" Style="{StaticResource EntryFieldStyle}" >
<TextBlock Margin="5,2" Text="This dissappears as the control gets focus..." Foreground="{StaticResource brushWatermarkForeground}" >
<TextBlock.Visibility>
<MultiBinding Converter="{StaticResource TextInputToVisibilityConverter}">
<Binding ElementName="txtUserEntry2" Path="Text.IsEmpty" />
<Binding ElementName="txtUserEntry2" Path="IsFocused" />
</MultiBinding>
</TextBlock.Visibility>
</TextBlock>
<TextBox Name="txtUserEntry2" Background="Transparent" BorderBrush="{StaticResource brushWatermarkBorder}" />
</Grid>

</Grid>

</Window>

TextInputToVisibilityConverter is defined as:

using System;
using System.Windows.Data;
using System.Windows;

namespace WaterMarkTextBoxDemo
{
public class TextInputToVisibilityConverter : IMultiValueConverter
{
public object Convert( object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture )
{
// Always test MultiValueConverter inputs for non-null
// (to avoid crash bugs for views in the designer)
if (values[0] is bool && values[1] is bool)
{
bool hasText = !(bool)values[0];
bool hasFocus = (bool)values[1];

if (hasFocus || hasText)
return Visibility.Collapsed;
}

return Visibility.Visible;
}

public object[] ConvertBack( object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture )
{
throw new NotImplementedException();
}
}
}

Note: This is not my code. I found it here, but I think this is the best approach.

C# - Watermark passwordchar?

Just set it and unset it as you do for the ForeColor :

    private void passwordLogin_Leave(object sender, EventArgs e){
if (passwordLogin.Text.Length == 0){
passwordLogin.Text = "Password";
passwordLogin.ForeColor = Color.Silver;
passwordLogin.PasswordChar = '\0';
}
}

private void passwordLogin_Enter(object sender, EventArgs e){
if (passwordLogin.Text == "Password"){
passwordLogin.Text = "";
passwordLogin.ForeColor = Color.Black;
passwordLogin.PasswordChar = '*';
}
}


Related Topics



Leave a reply



Submit