Live Chat Icon For mobile
Live Chat Icon

WinForms FAQ - TextBox

Find answers for the most frequently asked questions
Expand All Collapse All

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

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

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

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

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

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

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

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

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

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

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

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

Share with

Share on twitter
Share on facebook
Share on linkedin

Couldn't find the FAQs you're looking for?

Please submit your question and answer.