views:

131

answers:

3

I am trying to build a program that has a button, and everytime that button is clicked, it moves the button and adds to the score. However, I am trying to disable the Enter key, or suppress the command when pressed. Here is what I have so far

private void button1_Click(object sender, EventArgs e, KeyEventArgs k)
    {
        if (k.KeyCode == Keys.Enter)
        {
            k.SuppressKeyPress = true;
        }
        score = score + 10;
        timesClicked++;
        int rand1 = RandomNumber(1, 400);
        int rand2 = RandomNumber(1, 400);
        button1.Location = new Point(rand1, rand2);
        toolStripScore.Text = ("Your score is " + score);
        toolStripClicks.Text = ("You've clicked the button{0} times " + timesClicked);
        winCheck();
    }

This is what I added to prevent the enter key from going in.

if (k.KeyCode == Keys.Enter) { k.SuppressKeyPress = true; }

However it generates the error... "No overload for 'button1_Click' matches delegate 'System.EventHandler'" And when clicked to show the location, it opens the code for Form1.Designer and points to this this line. "this.button1.Click += new System.EventHandler(this.button1_Click);"

Any help on resolving this issue would be much appreciated.

+1  A: 

Your method signature does not match EventHandler delegate (that is, you cannot just add KeyEventArgs argument and get this working). You'll need to handle more than one event to do what you want (look at KeyDown or KeyPress events).

Alternatively, use MouseClick event instead of Click event.

max
@max I've tried putting both private void Form1_KeyDown(object sender, KeyEventArgs e)and private void button1_KeyDown(object sender, KeyEventArgs e)With the if statement in the program and neither of the things prevent the enter key from working.
Cistoran
@Cistorian try `MouseClick` event then, it should ignore enter key by design
max
@Max What do you mean try MouseClick? Try it with what?
Cistoran
try `MouseClick` instead of `Click`
max
A: 

Well, I think that the issue is in your decleration of button1_click(). An event handler can only have the signature of delegate void EventHandler( Object sender, EventArgs e ) So, take the Key press out of button1_click, and put it in a KeyPress event.

ChrisFeilen
A: 

EventHandle delegate, is two parameters, not three. and your method has three parameters, so it's wrong.

see:EventHandler delegate information in msdn

first, your have to modify your method:

private void button1_Click(object sender, EventArgs e)
{
}

and then judge the type in the method like this:

KeyEventArgs k = null;
if(e is KeyEventArgs){
    k = (KeyEventArgs) e;
    //do sth here about pressing 'enter'
}

delegate ,method must have the same parameters, the same return type, or it will be exception.

Tim Li