user16527648
user16527648

Reputation:

Reject Enter from activating the click action

I would like to help with my new clicker game that I'm working on and I've stumbled upon a problem with adding a value to the "playerPoints" which is from launch 0. You need to click a button which is called "button_click" which will add +1 (++) to your "playerPoints". But there is a bug when you click the button and then hold the enter button it will act like a little auto clicker which I don't want. Is there a way how to prevent the enter key to add value when it is pressed or held down? Thanks in exchange.

          int playerPoints = 0;

          public void button_click_Click(object sender, EventArgs e) // main click button
          {
           playerPoints++;
           label_points.Text = playerPoints.ToString() + " BITS";
          }

Upvotes: 0

Views: 69

Answers (3)

TnTinMn
TnTinMn

Reputation: 11801

When you click on the subject Button, it becomes the form's ActiveControl. As part of the form's internal processing in setting the ActiveControl, the Form.UpdateDefaultButton Method is called.

Remarks

The UpdateDefaultButton method determines which button on the form raises its Click event when the user presses ENTER, according to the following priority:

To avoid having the subject button becoming the Default Button, override the form's UpdateDefaultButton method with something like this:

protected override void UpdateDefaultButton()
{
    if (ActiveControl == button_click)
    {
        return;
    }
    else
    {
        base.UpdateDefaultButton();
    }
}

Upvotes: 1

user16527648
user16527648

Reputation:

The problem has been solved by an great idea by: Dan Byström If you don't want to make the button respond to keys like enter. Use a simple image or label and link that function to the image_click or label_click

again thanks alot guys!

Upvotes: 1

Doug
Doug

Reputation: 5328

Hook the KeyDown event instead of the Click event.

https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keydown

Button.KeyDown += Button_KeyDown;

// Handle the KeyDown event
private void Button_KeyDown(object sender, KeyEventArgs e)
{
   //increment your counter
}

Upvotes: 0

Related Questions