Cataldo
Cataldo

Reputation: 585

Problems with KeyPressEventArgs

here's my problem .. i'm doing a calculator in C# and i don't want to click every single button to make a operation, i wanna handle it with my num pad .. like if i press "1" , show me in the textbox "1".

i changed

private void cmd1_Click(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '1')
            {
                txtShow.Text='1';
            }
        }

and i'm having this error :

No overload for 'cmd1_Click' matches delegate "System.EventHandler"

this.cmd1.Click += new System.EventHandler(this.cmd1_Click);

what the hack is wrong with this?

Cheers.

Upvotes: 1

Views: 2262

Answers (3)

Ronan Thibaudau
Ronan Thibaudau

Reputation: 3603

Click is a mouse event, you need to attach to a keyboard event if you want to receive keyboard event args, you'd have to put all your calculator buttons in a common pannel and handle both the button click "and" the text being sent to the panel, that way you could react to both keypresses anywhere and to click for the same result.

An easy way to handling events for all the buttons without doing it one by one is to have a single button click handler and check the text property of the control to know how to act (cast the sender to a button and check the text, do a switch on that)

Not tested:

switch(((button)sender).Text)
{
    case "1":
          // react to user having pressed 1 etc etc
}

Upvotes: 0

Simon
Simon

Reputation: 5503

change

this.cmd1.Click += new System.EventHandler(this.cmd1_Click);

to

this.cmd1.KeyPress += new System.EventHandler(this.cmd1_Click);

You'll probably want to rename cmd1_Click too.

And as mentioned in the answer above, this would be better on the Form itself, rather than each button.

Upvotes: 2

ken2k
ken2k

Reputation: 49013

You are trying to attach an event handler that corresponds to a KeyPress event to a Click event.

There is something wrong here (bad copy/paste?):

private void cmd1_Click(object sender, KeyPressEventArgs e)

It's named as an auto-generated event handler for the Click event on cmd1, but its definition is the definition for a KeyPress event handler.

Which event do you want to handle? KeyPress or Click or both?

Upvotes: 1

Related Questions