Adding Events To WinForms?

前端 未结 5 1968
臣服心动
臣服心动 2020-12-11 19:58

I have a TextBox on a WinForm and I want to execute some code every time someone presses a key inside of that TextBox. I\'m looking at the events properties me

相关标签:
5条回答
  • 2020-12-11 20:37

    You need to add a handler to the event.

    Double-click the KeyPress event in the textbox's Properties window to make Visual Studio generate an event handler in the code file.
    You can then put any code you want to inside the event handler function. You can check which key was pressed by writing e.KeyCode.

    0 讨论(0)
  • 2020-12-11 20:39

    I assume you are in Visual Studio. One way would be to double click on the empty textbox on the right of the KeyDown event: VS will generate the code for you.

    0 讨论(0)
  • 2020-12-11 20:45

    These answers will have visual studio generate the event and bind it behind the scenes in the Designer.cs file.

    If you want to know how to bind events yourself, it looks like this.

    MyTextBox.KeyDown += new KeyEventHandler(MyKeyDownFunction)
    
    private function MyKeyDownFunction(object sender, KeyEventArgs e) {
        // your code
    }
    

    If done this way, the new KeyEventHandler() part is optional. You can also use lambdas to avoid boilerplate code.

    MyTextBox.KeyDown += (s, e) => {
        // s is the sender object, e is the args
    }
    
    0 讨论(0)
  • 2020-12-11 20:46

    Doubleclick the textfield next to it.

    0 讨论(0)
  • 2020-12-11 20:51

    You need to add an event handler for that event. So in the properties menu, double-click on the field beside the KeyDown event and Visual Studio will create an event handler for you. It'll look something like this:

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        // enter your code here
    }
    

    You can also subscribe to events yourself without using the Properties window. For example, in the form's constructor:

    textBox1.KeyDown += HandleTextBoxKeyDownEvent;
    

    And then implement the event handler:

    private void HandleTextBoxKeyDownEvent(object sender, KeyEventArgs e)
    {
        // enter your code here
    }
    
    0 讨论(0)
提交回复
热议问题