Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Forms Textbox Enter key

I have a TextBox, but I can't find any source explaining how to call a function when a button is pressed down.

public Simple()
{
    Text = "Server Command Line";
    Size = new Size(800, 400);

    CenterToScreen();

    Button button = new Button();
    TextBox txt = new TextBox ();

    txt.Location = new Point (20, Size.Height - 70);
    txt.Size = new Size (600, 30);
    txt.Parent = this;

    button.Text = "SEND";
    button.Size = new Size (50, 20);
    button.Location = new Point(620, Size.Height-70);
    button.Parent = this;
    button.Click += new EventHandler(Submit);
}

Some sources tell me to use a function, but I don't understand how it is going to get called.

like image 912
Statharas.903 Avatar asked Aug 05 '13 13:08

Statharas.903


People also ask

How do I insert a TextBox in Windows form?

Step 1: Create a windows form. Step 2: Drag the TextBox control from the ToolBox and Drop it on the windows form. You can place TextBox anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the TextBox control to set the Text property of the TextBox.

How do I add a button to Windows form?

Add the control by drawing Select the control by clicking on it. In your form, drag-select a region. The control will be placed to fit the size of the region you selected.


2 Answers

If I understood correctly you want to call a method when users press Enter while typing anything in textbox? If so, you have to use the KeyUp event of TextBox like this:

public Simple()
{
    Text = "Server Command Line";
    ...

    TextBox txt = new TextBox ();
    txt.Location = new Point (20, Size.Height - 70);
    txt.Size = new Size (600, 30);
    txt.KeyUp += TextBoxKeyUp; //here we attach the event
    txt.Parent = this;    

    Button button = new Button();
    ...
}

private void TextBoxKeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        //Do something
        e.Handled = true;
    }
}
like image 132
gzaxx Avatar answered Sep 24 '22 15:09

gzaxx


you already have a button as well like this

button.Click += new EventHandler(Submit); 

if you want to call this function you can do this

button.PerformClick();  //this will call Submit you specified in the above statement
like image 42
Ehsan Avatar answered Sep 25 '22 15:09

Ehsan