Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextBox to accept enter/return

Tags:

c#

winforms

I have the below code that allows a user to write in a executable (i.e. notepad.exe) and then clicking the start button it will start the process.

However, how do I make the TextBox accept enter/return key? I put in AcceptsReturn=true but it is not doing anything. I have also set in Visual Studio the property Accept Return = True - still nothing.

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace process_list
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string text = textBox1.Text;
            Process process = new Process();
            process.StartInfo.FileName = text;
            process.Start();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            textBox1.AcceptsReturn = true;
        }
    }
}
like image 762
lara400 Avatar asked Nov 14 '25 14:11

lara400


2 Answers

Set the AcceptButton of the form to your button. You don't need AcceptsReturn then, because Enter automatically triggers the button.

public Form1()
{
    InitializeComponent();
    this.AcceptButton = button1;
}
like image 64
Botz3000 Avatar answered Nov 17 '25 04:11

Botz3000


Add KeyDown event method to textBox1 and inside the method do this

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
        button1_Click(sender, e);
}
like image 45
th1rdey3 Avatar answered Nov 17 '25 03:11

th1rdey3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!