Same method but different events

  • Thread starter Thread starter Ramsin Savra
  • Start date Start date
R

Ramsin Savra

Hi Group,

How can I define one function but able to use it in different events? let's
say I have a method which should be called in KeyPress and KeyDown and Click
either ?

thanks
 
Ramsin Savra said:
Hi Group,

How can I define one function but able to use it in different events? let's
say I have a method which should be called in KeyPress and KeyDown and Click
either ?

thanks

Click, KeyPress and KeyDown events all use a different delegate (since
they all pass different parameters), so you can't assign the same
event handler to these events.

You'd have to do something like this:

private void button1_Click(object sender, System.EventArgs e)
{
DoSomething();
}

private void button1_KeyDown(object sender,
System.Windows.Forms.KeyEventArgs e)
{
DoSomething();
}

private void button1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
DoSomething();
}

private void DoSomething()
{
// ...common code here...
}
 
Hi Group,

How can I define one function but able to use it in different events? let's
say I have a method which should be called in KeyPress and KeyDown and Click
either ?

Just call the function. Something like this:

public void KeyPressHandler(...)
{
MyFunction();
}

public void KeyDownHandler(...)
{
MyFunction();
}

private void MyFunction()
{
...
}
 
Ramsin said:
Hi Group,

How can I define one function but able to use it in different events?
let's say I have a method which should be called in KeyPress and
KeyDown and Click either ?

If they all share a common signature, simply create your delegates with your
event handler as the parameter. Better yet, if they all use a common
delegate, make a single delegate and add it to all three event sinks.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
 
Back
Top