WinForms FAQ - TextBox

When I set a TextBox to Readonly or set Enabled to false, the text color is gray. How can I force it to be the color specified in the ForeColor property of the TextBox.

Felix Wu gives this solution in the microsoft.public.dotnet.frameworks.windowsforms newgroup.

You can download a VB.NET sample.

Override the OnPaint event of the TextBox. For example:

protected override void OnPaint(PaintEventArgs e)
{
  SolidBrush drawBrush = new SolidBrush(ForeColor); //Use the ForeColor property
  // Draw string to screen.
  e.Graphics.DrawString(Text, Font, drawBrush, 0f,0f);  //Use the Font property
}

Note: You need to set the ControlStyles to ”UserPaint” in the constructor.

public MyTextBox()
{
  // This call is required by the Windows.Forms Form Designer.
  this.SetStyle(ControlStyles.UserPaint,true); 

  InitializeComponent();

  // TODO: Add any initialization after the InitForm call
}
Permalink
How can I place a TextBox in overwrite mode instead of insert mode

You can handle the textbox’s KeyPress event and if you want the keypress to be an overwrite, just select the current character so the keypress will replace it. The attached sample has a derived textbox that has an OverWrite property and a right-click menu that allows you to toggle this property.

The snippet below shows you a KeyPress handler that automatically does an overwrite if the maxlength of the textbox has been hit. This does not require a derived class.

private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
  if(textBox1.Text.Length == textBox1.MaxLength && textBox1.SelectedText == '''')
  {
    textBox1.SelectionLength = 1;
  }
}
Permalink
How can I use a TextBox to enter a password

Set the TextBox.PasswordChar property for the textbox.

	textBox1.PasswordChar = ’\u25CF’;
Permalink
How do I format numbers, dates and currencies in a TextBox

Each type has a ToString method that can be used to accomplished formatting. Also, you can use the String.Format method to format things as well. To format dates, use the ToString member of DateTime. You may want to use the InvariantInfo setting (see below) to get culture-independent strings.

Permalink
How do I set several lines into a multiline textbox

There are a several of ways to do this. Here are a few:

1) Insert a carriage return-linefeed, ‘\r\n’, between your lines.

		textBox1.Text = 'This is line 1.\r\nThis is line 2';
		// or textBox1.Text = stringvar1 + '\r\n' + stringvar2;

2) Use the Environment.NewLine property. This property is normally set to ‘\r\n’.

		textBox1.Text = 'This is line 1.' + Environment.NewLine + 'This is line 2';

3) Use the Lines property of the TextBox. Make sure you populate your array before you set the property.

		string[] arr = new string[2];
		arr[0] = 'this is line1';
		arr[1] = 'this is line 2';

		textBox3.Lines = arr;
Permalink
How do I browse for, and read a text file into an TextBox

You use the Frameworks OpenFileDialog to implement this functionality.

	using System.Text;
	using System.IO;
	....
	private void button1_Click(object sender, System.EventArgs e)
	{
		OpenFileDialog dlg = new OpenFileDialog(); 
		dlg.Title = 'Open text file' ; 
		dlg.InitialDirectory = @'c:\' ; 
		dlg.Filter = 'txt files (*.txt)|*.txt|All files (*.*)|*.*' ; 
		 
		if(dlg.ShowDialog() == DialogResult.OK) 
		{ 
			StreamReader sr = File.OpenText(dlg.FileName);

			string s = sr.ReadLine();
			StringBuilder sb = new StringBuilder();
			while (s != null)
			{
				sb.Append(s);
				s = sr.ReadLine();
			}
			sr.Close();
			textBox1.Text = sb.ToString();
		} 
	}
Permalink
How can I prevent the beep when enter is hit in textbox?

You can prevent the beep when the enter key is pressed in a TextBox by deriving the TextBox and overriding OnKeyPress.

[C#]
public class MyTextBox : TextBox
{
	protected override void OnKeyPress(KeyPressEventArgs e)
	{
		if(e.KeyChar == (char) 13)
			e.Handled = true;
		else
			base.OnKeyPress (e);
	}
}
[VB.NET]
Public Class MyTextBox
	Inherits TextBox
   
	Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs)
		If e.KeyChar = CChar(13) Then
			e.Handled = True
		Else
			MyBase.OnKeyPress(e)
		End If
	End Sub ’OnKeyPress
End Class ’MyTextBox
Permalink
How do I disable pasting into a TextBox (via Ctrl + V and the context menu)?

First set the ContextMenu property of the TextBox to a dummy, empty ContextMenu instance. This will prevent the default context menu from showing. Then, override the ProcessCmdKey method as follows in a TextBox derived class:

		// In C#
		protected override bool ProcessCmdKey(ref Message msg,	Keys keyData)
		{
			if(keyData == (Keys.Control | Keys.V))
				return true;
			else
				return base.ProcessCmdKey(ref msg, keyData);
		}
		’ In VB.Net
		Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
			If keyData =(Keys.Control | Keys.V) Then
				Return True
			Else 
				Return MyBase.ProcessCmdKey( msg, keyData)
			End If
		End Function
Permalink
How can I disable the right-click context menu in my textbox

You can set the ContextMenu property of the TextBox to a dummy, empty ContextMenu instance.

Permalink
How can I make a ReadOnly TextBox ignore the mousedowns so that you cannot scroll the text or set the cursor

You can do this by deriving the TextBox, overriding the WndProc method and ignoring these mousedowns.

[C#]
public class MyTextBox : TextBox
{
	protected override void WndProc(ref System.Windows.Forms.Message m)
	{	// WM_NCLBUTTONDOWN  WM_LBUTTONDOWN 
		if(this.ReadOnly && (m.Msg ==  0xa1 || m.Msg == 0x201))
		{
			return; //ignore it
		}
		base.WndProc(ref m);
	}
}
[VB.NET]
Public Class MyTextBox
	Inherits TextBox
    
	Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
		’ WM_NCLBUTTONDOWN  WM_LBUTTONDOWN 
		If Me.ReadOnly AndAlso(m.Msg = &HA1 OrElse m.Msg = &H201) Then 
			Return ’ignore it
		End If
		MyBase.WndProc(m)
	End Sub ’WndProc
End Class ’MyTextBox
Permalink
How do I prevent a control from receiving focus when it receives a mouseclick

You can set the control’s Enabled property to false. This will prevent clicking but also gives the disabled look.

There is a ControlStyles.Selectable flag that determines whether the control can get focus or not. But it does not appear to affect some controls such as TextBox. But you can prevent the TextBox from getting focus by overriding its WndProc method and ignoring the mouse down.

public class MyTextBox : TextBox
{
	const int WM_LBUTTONDOWN = 0x0201;
  
	protected override void WndProc(ref System.Windows.Forms.Message m)
	{
		if(m.Msg == WM_LBUTTONDOWN)
			return;
		base.WndProc(ref m);
	}
}
Permalink
How can I make the focus move to the next control when the user presses the Enter key in a TextBox

Add a handler for your TextBox’s KeyDown event. (This assumes you set the AcceptsReturn property to False).

Then in your KeyDown eventhandler, have code such as:

[C#]
	if (e.KeyCode = Keys.Enter)
		SendKeys.Send('{TAB}');
       
[VB.NET]
	If e.KeyCode = Keys.Enter Then
		SendKeys.Send('{TAB}')
	EndIf
Permalink
How can I restrict the characters that my textbox can accept

You can handle the textbox’s KeyPress event and if the char passed in is not acceptable, mark the events argument as showing the character has been handled. Below is a derived TextBox that only accepts digits (and control characters such as backspace, …). Even though the snippet uses a derived textbox, it is not necessary as you can just add the handler to its parent form.

[C#]
public class NumbersOnlyTextBox : TextBox
{
	public NumbersOnlyTextBox()
	{
		this.KeyPress += new KeyPressEventHandler(HandleKeyPress);
	}

	private void HandleKeyPress(object sender, KeyPressEventArgs e)
	{
		if(!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
			e.Handled = true;
	}
}

[VB.NET]
Public Class NumbersOnlyTextBox
	Inherits TextBox
   
	Public Sub New()
		AddHandler Me.KeyPress, AddressOf HandleKeyPress
	End Sub ’New
   
	Private Sub HandleKeyPress(sender As Object, e As KeyPressEventArgs)
		If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
			e.Handled = True
		End If
	End Sub ’HandleKeyPress
End Class ’NumbersOnlyTextBox
Permalink
How to get rid of the gong sound when enter is hit in textbox?

Subclass from TextBox, override ProcessDialogKey and do the following:

protected override bool ProcessDialogKey(Keys keyData)
{
	if(keyData == Keys.Return)
	{
		return true;
	}
	else if(keyData == Keys.Escape)
	{
		return true;
	}
	else
		return base.ProcessDialogKey(keyData);
}

The idea is to prevent the base class from processing certain keys.

Permalink
I have a delete key shortcut for my main menu. When my textbox is being edited, pressing delete activates this menu items instead of being processed by the TextBox. How can I get my TextBox to handle this delete

Subclass the TextBox and override its PreProcessMessage method.

public class MyTextBox : TextBox
{

	const int WM_KEYDOWN = 0x100;
	const int WM_KEYUP = 0x101;

	public override bool PreProcessMessage(	ref Message msg )
	{
		Keys keyCode = (Keys)(int)msg.WParam & Keys.KeyCode;
		if((msg.Msg == WM_KEYDOWN || msg.Msg == WM_KEYUP)
			&& keyCode == Keys.Delete)
		{
			return false;
		}	
		return base.PreProcessMessage(ref msg);
	}
}
Permalink
How do I make my textbox use all upper (or lower) case characters

Use the CharacterCasing property of the TextBox.

textBox1.CharacterCasing = CharacterCasing.Upper;
// textBox1.CharacterCasing = CharacterCasing.Lower;
Permalink
How do I send a EM_XXXX message to a textbox to get some value such as line index in C#

There is a protected SendMessage call you can use for this purpose, so you have to derive from TextBox.

	public MyTextBox : TextBox 
	{
		private const int EM_XXXX = 0x1234;
		public int LineIndex 
		{
			get 
			{
            				return base.SendMessage(EM_XXXX, 0, 0);
        			}
    		}
	}

(from sburke_online@microsoft..nospam..com on microsoft.public.dotnet.framework.windowsforms)

Permalink