I'm making a Login form with two text boxes(username, password) and a button called "Login". I would like to simulate the Login click when the user finishing enter the password and press the "Enter" key. Could someone tell me how to go about doing this? Thanks in advance.

Depends on the operating system. For MS-Windows see LogonUser win32 api function

I was digging around and found the answer to my question. You can use the keypress event to trigger the button click.

private void txtMessage_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar.Equals(Convert.ToChar(13)))
{
btnLogin_Click(sender, e);
}
}

Try out this code:

        TextBox[] tbs;
        public Form1()
        {
            InitializeComponent();
            tbs = new TextBox[2] { textBox1, textBox2 };

            //create same event for both textboxes
            for (int i = 0; i < tbs.Length; i++)
            {
                tbs[i].KeyDown += new KeyEventHandler(TextBoxes_KeyDown);
            }            
        }

        private void TextBoxes_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                bool bContinue = true;
                //1 checking if both textboxes have values
                foreach (TextBox tb in tbs)
                {
                    if (String.IsNullOrEmpty(tb.Text))
                    {
                        bContinue = false;
                        break;
                    }
                }
                if (bContinue)
                {
                    //data are inserted, and enter key is presses,
                    //you can continue to validate these data here                    
                }
                else
                    MessageBox.Show("Please enter data to textBoxes...");
            }
        }

All you have to do is set the "AcceptButton" property of the form to that button. This property causes the button_click even to fire when the user presses enter.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.