Question

Is an easy way to cancel click event when user hit enter on button (instead of mouse click on button?)

i have tried with:

    private void button3_Click(object sender, EventArgs e)
    {
        KeyEventArgs ke = e as KeyEventArgs;
        if (ke != null)
        {
            if (ke.KeyCode == Keys.Enter)
            {
                return;
            }

        }
    }

But ke is null

Was it helpful?

Solution

public void btnClick(object sender, EventArgs e)
{
  bool IsMouse = (e is System.Windows.Forms.MouseEventArgs);

  // If not mouse, they hit spacebar or enter
}

OTHER TIPS

Yes it will be null. because EventArgs is not KeyEventArgs

KeyEventArgs will be passed as a parameter to KeyDown or KeyUp events. You're messing up things.

You can do something like this

private bool flag = false;
private void button1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Return)
    {
        flag = true;
    }
}

private void button1_Click(object sender, EventArgs e)
{
    if (flag)
    {
        flag = false;
        return;
    }
    //else do original task
}

You can handle KeyPress event for the button and disable or ignore enter key there instead of returning in button click

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if ((keyData & Keys.KeyCode) == Keys.Enter)
            {
                SendKeys.Send("{Tab}");
                return true;
            }
            return false;
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top