Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
how do that when hit the enter form key board then submit the form
Posted

try this :)
C#
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
       {
           if (keyData == Keys.Enter)
           {
              //submit logic
           }

           return base.ProcessCmdKey(ref msg, keyData);
       }
 
Share this answer
 
Comments
Tarun.K.S 9-May-11 10:01am    
Right but I liked the idea of Kim. 5+
ambarishtv 9-May-11 10:10am    
thanks Tarun.I also agree
Kim Togo 9-May-11 10:19am    
Good one :-). My 5.
ambarishtv 9-May-11 10:28am    
thanks.
yours is an excellent answer.My5
You can set AcceptButton[^] property to the button in your Form what handles the data entered.

As SA has pointed out, AcceptButton property makes sense when used with form1.ShowDialog(). And remember, just setting the AcceptButton/CancelButton is not enough. This just tell which button should be invoked on ENTER/ESC. We have to set the DialogResult in the Button handler.

button1.DialogResult = System.Windows.Forms.DialogResult.OK;
button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;

form1.AcceptButton = button1;
form1.CancelButton = button2;
 
Share this answer
 
v3
Comments
Tarun.K.S 9-May-11 10:01am    
Excellent answer Kim. 5+
Kim Togo 9-May-11 10:14am    
Thanks Tarun.
Sergey Alexandrovich Kryukov 9-May-11 10:29am    
Kim, I did not vote. You should have explain that this is relevant only to a modal form and it needs a code running ShowDialog and checkning modal result, otherwise this makes no sense at all.
--SA
Kim Togo 9-May-11 13:19pm    
Thanks for the info. I have updated my answer.
Sergey Alexandrovich Kryukov 9-May-11 21:21pm    
Thanks for the note. I up-voted it by another 5.
--SA
You can set form1.KeyPreview = true; and handle event form1.KeyDown.
Setting KeyPreview to true, then the form will receive key events before the event is passed to the control that has focus

C#
form1.KeyPreview = true;
form1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.form1_KeyDown);


Method to suppress ENTER button.

C#
private void form1_KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyData == Keys.Enter)
  {
    e.SuppressKeyPress = true; // Event should not be sent to the control
    SaveData(); // Get data in form and save.
  }
}
 
Share this answer
 
v2
Comments
ambarishtv 9-May-11 10:22am    
hi,
it works when hit enter key two times.
Kim Togo 9-May-11 13:21pm    
Weird ? - I will try it out my self :-)
Sergey Alexandrovich Kryukov 9-May-11 10:30am    
Better. My 5.
--SA
Kim Togo 9-May-11 13:19pm    
Thanks SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900