electricalbah
electricalbah

Reputation: 2297

Call a button event from a function

I want to call a button event in a function as shown below, This might not be the right way. If you have idea how to go around this please share some sample on how to achieve it. Thanks

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
    {
        const int WM_KEYDOWN = 0x100;
        const int WM_SYSKEYDOWN = 0x104;

        if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
        {
            switch (keyData)
            {
              case Keys.Down:
              button4_Click(sender, e); //error: sender and e does not exist in the current context
              break;
            }
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }

Upvotes: 0

Views: 497

Answers (3)

gzaxx
gzaxx

Reputation: 17590

Why do not move button4_Click code to other method like ProcessSomething() and do processing there. Then just change

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{
    const int WM_KEYDOWN = 0x100;
    const int WM_SYSKEYDOWN = 0x104;

    if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
    {
        switch (keyData)
        {
          case Keys.Down:
          ProcessSomething();
          break;
        }
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

you can fire button4_Click method by passing nulls to it but IMO it is not elegant to fire events like that.

Upvotes: 1

roybalderama
roybalderama

Reputation: 1640

Try this:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{
    const int WM_KEYDOWN = 0x100;
    const int WM_SYSKEYDOWN = 0x104;

    if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
    {
        switch (keyData)
        {
          case Keys.Down:
          button4_Click(null, null);
          break;
        }
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

Upvotes: 2

Carlos Landeras
Carlos Landeras

Reputation: 11063

Call button4 click passing itself as sender and new System EventArgs as second parameter:

button4_Click(button4, new System.EventArgs());

Upvotes: 0

Related Questions