C# coding question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • atgcpaul
    Veteran Member
    • Aug 2003
    • 4055
    • Maryland
    • Grizzly 1023SLX

    #1

    C# coding question

    I'm learning C# and am stuck. I want to be able to hit the Enter key while my
    cursor is in a text box and have it act as if I had clicked a button. I know I
    can wire different events in the form to the button_click event handler. It
    seems like this would be a simple matter but I'm not finding the right event to
    use. You would think the Enter event would be it, but that seems to only act if
    you enter the text box by tabbing or clicking on it, and not by hitting Enter
    while in the text box.

    I had limited success with the KeyDown event but it's not perfect. What am I
    missing here?

    Thanks, Paul
  • Alex Franke
    Veteran Member
    • Feb 2007
    • 2641
    • Chapel Hill, NC
    • Ryobi BT3100

    #2
    Handle TextBox KeyDown event and trap for e.KeyCode == Keys.Enter to call the same method that the button click calls.

    Edit: Some code - hopefully this will compile

    First create a new form and add a Button called "MyButton" and a TextBox called "MyTextBox". In the form's constructor (something like "Form1()") add this to wire up the events:

    Code:
    MyButton.Click += new EventHandler(MyButton_Click);
    MyTextBox.KeyDown += new KeyEventHandler(MyTextBox_KeyDown);
    Then add these functions in the form file to handle the events.

    Code:
    private void MyTextBox_KeyDown( object sender, KeyEventArgs e )
    {
        if ( e.KeyCode == Keys.Enter )
          DoSomething(); 
    }
    
    private void MyButton_Click( object sender, EventArgs e )
    {
        DoSomething(); 
    }
    
    private void DoSomething()
    {
        Console.WriteLine( "Doing something" ); 
    }
    Another edit: Alternatively, you can call the actual button click event handler from the Keydown handler, but you'll have to make up a new eventarg for the button click. If you don't care about the mouse location where the button was clicked, you can just give it a new EventArgs(). If you do care about the mouse event args, let me know and I can walk you through it.
    Last edited by Alex Franke; 02-16-2009, 02:22 PM.
    online at http://www.theFrankes.com
    while ( !( succeed = try() ) ) ;
    "Life is short, Art long, Occasion sudden and dangerous, Experience deceitful, and Judgment difficult." -Hippocrates

    Comment

    • Alex Franke
      Veteran Member
      • Feb 2007
      • 2641
      • Chapel Hill, NC
      • Ryobi BT3100

      #3
      I should point this out, too: If the button you're trying to "autoclick" is supposed to act as a sort of default button for the form (e.g. if you have a dialog and you want the enter key to function the same was as closing the dialog with the OK button), then there's a more appropriate way to do this.

      Let me know if this is the case, and I can help with you with that, too.
      online at http://www.theFrankes.com
      while ( !( succeed = try() ) ) ;
      "Life is short, Art long, Occasion sudden and dangerous, Experience deceitful, and Judgment difficult." -Hippocrates

      Comment

      • atgcpaul
        Veteran Member
        • Aug 2003
        • 4055
        • Maryland
        • Grizzly 1023SLX

        #4
        Originally posted by Alex Franke
        Another edit: Alternatively, you can call the actual button click event handler from the Keydown handler, but you'll have to make up a new eventarg for the button click. If you don't care about the mouse location where the button was clicked, you can just give it a new EventArgs().
        Thanks, Alex. This is what I was looking for.

        I got it to work by creating a new EventArgs(), but is there a more "elegant"
        way to do it? What I mean is, I have a method MyButton_Click that is
        executed when the button is clicked, but when an Enter key is pressed, a
        different method EventArgs() is called which has all the same code as
        MyButton_Click. It just seems redundant. Is this because I can't call
        MyButton_Click from within the MyTextBox_KeyDown method because there
        are no arguments to pass?

        Hope this is clear, and I hope this doesn't sound ungrateful,
        Paul

        Comment

        • Alex Franke
          Veteran Member
          • Feb 2007
          • 2641
          • Chapel Hill, NC
          • Ryobi BT3100

          #5
          Originally posted by atgcpaul
          I got it to work by creating a new EventArgs(), but is there a more "elegant" way to do it? What I mean is, I have a method MyButton_Click that is executed when the button is clicked, but when an Enter key is pressed, a different method EventArgs() is called which has all the same code as MyButton_Click. It just seems redundant. Is this because I can't call MyButton_Click from within the MyTextBox_KeyDown method because there are no arguments to pass?
          Elegance is a great thing to strive for in code and redundancy is a great thing to avoid!

          You can put all the duplicated code in the DoSomething() function and call that one from each event handler. This is probably the clearest way to do it -- especially if you're not using anything provided to the button click handler (object sender or EventArgs e).

          If your button click handler has a bunch of references to sender and e, then it depends on how you use e. A click event often contains mouse information (if the user clicked with a mouse), but if you don't need any of that information, you can just call the event handler with a new EventArgs or even a null.

          Like this:
          Code:
          private void MyTextBox_KeyDown( object sender, KeyEventArgs e )
          {
              if ( e.KeyCode == Keys.Enter )
                MyButton_Click( MyButton, null );
          }
          If you don't use any references to "sender" in your button click handler, then you can use null for that, too ( "MyButton_Click( null, null );" ) but if you can get away with this, it means you should probably do it the first way I mentioned and create a method specifically for what you're trying to do -- like the DoSomething() call.

          Originally posted by atgcpaul
          Hope this is clear, and I hope this doesn't sound ungrateful,
          Nope, it doesn't sound ungrateful.
          online at http://www.theFrankes.com
          while ( !( succeed = try() ) ) ;
          "Life is short, Art long, Occasion sudden and dangerous, Experience deceitful, and Judgment difficult." -Hippocrates

          Comment

          • Alex Franke
            Veteran Member
            • Feb 2007
            • 2641
            • Chapel Hill, NC
            • Ryobi BT3100

            #6
            I guess another way to do it would be to just use the same event handler for both events. you can do this because KeyEventArgs extends EventArgs. So there would be nothing to stop you from doing something like this when you wire it up:

            Code:
            MyButton.Click += new EventHandler(MyButton_Click);
            MyTextBox.KeyDown += new KeyEventHandler(MyButton_Click);
            ...but then you'd have a bit of an unintuitive kludge when you handle that event because you'd have to see which even you're really handling... something like this: (I don't think this is as clear, though, but it might be more along the lines of what you're looking for... You'd probably want to rename the handler, too, to clarify that it's not just handling the button click.)

            Code:
            private void MyButton_Click( object sender, EventArgs e )
            {
                KeyEventArgs keyargs = e as KeyEventArgs;
                if ( ( keyargs != null ) && ( keyargs.KeyCode != Keys.Enter ) )
                    return; // get out because we got a non-"enter" in a KeyDown somwhere
               
                // the rest of your event handling code here... 
            }
            Last edited by Alex Franke; 02-16-2009, 03:31 PM.
            online at http://www.theFrankes.com
            while ( !( succeed = try() ) ) ;
            "Life is short, Art long, Occasion sudden and dangerous, Experience deceitful, and Judgment difficult." -Hippocrates

            Comment

            • jkristia
              Established Member
              • Jan 2006
              • 114
              • Simi Valley, CA

              #7
              If you are trying to close a dialog on Esc/Enter then it is as simple as hooking up "DialogResult = OK" on the OK button (and DialogResult = Cancel" for the cancel button and then set the AcceptButton on the form to your OK buttnad and CancelButton to your cancel button. Then you have a 'normal' working dialog which will close with OK on Enter and Cancel on Esc. Both can be set from the property editor in the designer so you wont have to write a single line of code (for this)

              Jesper

              Comment

              • atgcpaul
                Veteran Member
                • Aug 2003
                • 4055
                • Maryland
                • Grizzly 1023SLX

                #8
                Originally posted by jkristia
                AcceptButton
                Jesper
                I just discovered this little gem, too. It almost seems like cheating to use this
                but it definitely saves on the coding.

                It was also good to learn about the KeyEventHandler because I can code
                different events for different textboxes based on different key entries. I don't
                know how I'd use this at the moment, but you never know.

                Thanks for the help, guys!

                Paul

                Comment

                Working...