Redirect the Enter key from a Windows Forms T...

来源:百度文库 编辑:神马文学网 时间:2024/04/28 16:18:26
 
3,677,243 members and growing!   6,189 now online.txjchen |My Settings |My Bookmarks |My Articles |Sign out
HomeMFC/C++C#ASP.NET.NETVB.NETAll Topics  Help!ArticlesMessage BoardsStoreFrontLounge
All Topics,C#,.NET >>C# Controls >>Edit Controls
Redirect the Enter key from a Windows Forms TextBox
ByJerome RG.
A useful trick to customize the comportment of the Enter key in a Windows Forms TextBox control.
MC++, C#
Windows, .NET
Win32, VS
Dev
Posted: 18 Feb 2006
Updated: 24 Feb 2006
Views: 14,815
Announcements
$10,000 worth of prizes to be wonMonthly Competition

Search   Articles Authors   Advanced Search
Sitemap |Add to IE Search
PrintBroken Article?BookmarkDiscussSend to a friend
7 votes for this article.
Popularity: 3.58. Rating: 4.23 out of 5.
You are signed up for one or morenewsletters but unfortunately we are unable to send you emails. Please clickhere to have an email sent that will allow us to confirm your email address.
Download source files - 15.9 KbDownload demo project - 4.48 Kb

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#:
Collapse
//! 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 public class CustomizedTextBox : System.Windows.Forms.TextBox { // This method intercepts the Enter Key // signal before the containing Form does protected override bool ProcessCmdKey(ref System.Windows.Forms.Message m, System.Windows.Forms.Keys k) { // detect the pushing (Msg) of Enter Key (k) 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("\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 base.ProcessCmdKey(ref m,k); } }
The code in managed C++:
Collapse
//! 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 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 (Msg) of Enter Key (k) 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); } }; 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.
About Jerome RG
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. Clickhere to view Jerome RG‘s online profile.
Other popular C# Controls articles:
Themed Windows XP style Explorer Bar A fully customizable Windows XP style Explorer Bar that supports Windows XP themes and animated expand/collapse with transparency.
XPTable - .NET ListView meets Java‘s JTable A fully customisable ListView style control based on Java‘s JTable.
SourceGrid - Open Source C# Grid Control SourceGrid is a free open source grid control. Supports virtual grid, custom cells and editors, advanced formatting options and many others features
TaskbarNotifier, a skinnable MSN Messenger-like popup in C# and now in VB.NET too The TaskbarNotifier class allows to display an MSN Messenger-like animated popup with a skinned background
[Top] Rate this Article for us!     PoorExcellent


FAQ  Message score threshold 1.0 2.0 3.0 4.0 5.0    Search comments
View Normal (slow) Preview (slow) Message View Topic View Thread View Expanded (Supporters only)    Per page 10 25 50
New Message Msgs 1 to 2 of 2 (Total: 2) (Refresh) First Prev Next
Subject  Author  Date

 Easiest Method  alexreg  7:14 25 Dec ‘06
  Nice work arounds you have there, and they seemed to me like the perfect solution after wasting a fair bit of time on this problem! However, just as I will solving it I found that for every multiline textbox that you don‘t want to click the AcceptButton on enter, all you have to do is set its AcceptReturn property to true! This is poorly documented of course, and took me a while to discover, so I hope this helps other coders in this situation.
[Reply |Email |View Thread |Get Link] Score: 2.0 (1 vote). Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Alternative method  Sidonath  12:39 23 Mar ‘06
  I needed to redirect Enter key on only one ComboBox, so I tried to come up with another solution. Solution which wouldn‘t require me to create new controls for one specific task. Eventually I did.
What I did was to dereference AcceptButton in PreviewKeyDown event (this.AcceptButton = null;), and then reassign it in KeyDown event (this.AcceptButton = btnOk;).
It is pretty silly, but hey, it works
[Reply |Email |View Thread |Get Link] Score: 2.0 (1 vote). Rate this message:12345 (out of 5)
Report asSpam orAbuse

Last Visit: 23:41 Wednesday 3rd January, 2007 First Prev Next
General comment   News / Info   Question   Answer   Joke / Game   Admin message
Updated: 24 Feb 2006 Article content copyright Jerome RG, 2006
everything else Copyright ©CodeProject, 1999-2006.
Web15 |Advertise on The Code Project |Privacy

The Ultimate Toolbox •ASP Alliance •Developer Fusion •Developersdex •DevGuru •Programmers Heaven •Planet Source Code •Tek-Tips Forums •
Help!
Articles
Message Boards
StoreFront
Lounge
What is ‘The Code Project‘?
General FAQ
Post a Question
Site Directory
About Us
Latest
Most Popular
Search
Site Directory
Submit an Article
Update an Article
Article Competition
Windows Vista
Visual C++
ATL / WTL / STL
COM
C++/CLI
C#
ASP.NET
VB.NET
Web Development
.NET Framework
Mobile Development
SQL / ADO / ADO.NET
XML / XSL
OS / SysAdmin
Work Issues
Article Requests
Collaboration
General Discussions
Hardware
Algorithms / Math
Design and Architecture
Subtle Bugs
Suggestions
The Soapbox