Click here to Skip to main content
15,894,343 members
Articles / Programming Languages / C#

Redirect the Enter key from a Windows Forms TextBox

Rate me:
Please Sign up or sign in to vote.
4.68/5 (13 votes)
24 Feb 20061 min read 126.9K   1.5K   45  
A useful trick to customize the comportment of the Enter key in a Windows Forms TextBox control.
// This .Net Solution demonstrates how to inherite from TextBox
// in order to customize the Enter Key comportment
// Written by Jerome RG (jeromerg@gmx.net)

#pragma once
using namespace System;

namespace Cplusplus
{


	/// <summary>
	/// Use instances of this class instead of TextBox in order to Redirect the process of the Enter Key, before the Form does it for you	
	/// </summary>
	public __gc class CustomizedTextBox : public System::Windows::Forms::TextBox 
	{	
	protected:

		// This method intercepts the Enter Key signal before the containing Form does
		virtual bool ProcessCmdKey(System::Windows::Forms::Message * m, System::Windows::Forms::Keys k) 
		{
			// detect the pushing of Enter Key
			if(m->Msg == 256 && k == System::Windows::Forms::Keys::Enter) 
			{
				// Execute an alternative action: here we tabulate in order to focus on the next control in the formular
				System::Windows::Forms::SendKeys::Send(S"\t");
				// return true to stop any further interpretation of this key action
				return true; 
			}
			// if not pushing Enter Key, then process the signal as usual
			return __super::ProcessCmdKey(m,k);
		}
	};
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Germany Germany
Jerome RG studied Computer Science in France and Germany. He obtained a Master Degree in Computer Science of the Technical University of Berlin. In September 2005, he built with two colleagues a company developing IT Solutions for aeronautics.

Comments and Discussions