
Introduction
Would you like to prevent the Enter key in a TextBox from automatically pressing the OK button of a Form, assuming you attached a OK button to the AcceptButton property of the Form?
The common way to redirect keys is to intercept their interpretation by attaching a method to the event handlers KeyPress or KeyDown of the TextBox control, or to derive from the class TextBox in order to override the methods OnKeyPress or OnKeyDown. Unfortunately, in this case, it fails: the redirection code is not interpreted and the OK button is automatically activated by the form itself. It happens because the parent form intercepts and stops the KeyPress and KeyDown signals. You don't get better results by overriding ProcessKeyPreview.
Instead, you have to inherit from TextBox and override the ProcessCmdKey virtual method.
The following C++ and C# code snippets show how to apply a tabulation when the user presses Enter, so that it switches to the next control.
Using the code
If you would like to use this code in your program, simply paste the class declaration in your code, and use CustomizedTextBox instead of System.Windows.Forms.TextBox in your code. If you want to enable the use of this control in the Forms Editor, then you should make a separate library project and import the contents of the DLL into the Visual Studio ToolBox.
The code in C#:
public class CustomizedTextBox : System.Windows.Forms.TextBox
{
protected override bool ProcessCmdKey(ref
System.Windows.Forms.Message m,
System.Windows.Forms.Keys k)
{
if(m.Msg == 256 && k ==
System.Windows.Forms.Keys.Enter)
{
System.Windows.Forms.SendKeys.Send("\t");
return true;
}
return base.ProcessCmdKey(ref m,k);
}
}
The code in managed C++:
public __gc class CustomizedTextBox :
public System::Windows::Forms::TextBox
{
protected:
virtual bool ProcessCmdKey(System::Windows::Forms::Message
* m, System::Windows::Forms::Keys k)
{
if(m->Msg == 256 && k ==
System::Windows::Forms::Keys::Enter)
{
System::Windows::Forms::SendKeys::Send(S"\t");
return true;
}
return __super::ProcessCmdKey(m,k);
}
};
Points of Interest
I hope this code will prevent some of you from wasting 3 or 4 hours looking for a trick that is not really (conceptually) interesting, but useful.
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.