简体   繁体   中英

C# How to use the EventHandler?

I'm just creating a ContextMenu..

At this line, I don't know what I shall put in the third param (or better: how I have to form it -syntaxly-):

(contextMenuStrip.Items[0] as System.Windows.Forms.ToolStripMenuItem).DropDownItems.Add(contextUnterMenuStrip.Items.Add(exe),null, HERE);

on 'HERE' I have to set an EventHandler onClick

By Example I got this Method:

public void DoSomething()
{
//...
}

How could I call this Method? (Over the Eventhandler?) or do I have to make a Method like:

private void button_Click(object sender, RoutedEventArgs e)
{
    //...
}

Don't "call" the method but take its address. Which means omitting the ()

private void menuItem1_Click(object sender, EventArgs e)
{
    //...
}


// your code, I think it misses a few ')'
... (contextMenuStrip.Items[0] as System.Windows.Forms.ToolStripMenuItem)
       .DropDownItems.Add(contextUnterMenuStrip.Items
       .Add(exe),null, menuItem1_Click);

As you can see here , the callback has to have the following prototype:

public delegate void EventHandler( Object sender, EventArgs e )

So your method DoSomething has to look like:

private void DoSomething(object sender, EventArgs e)
{
    //...
}

You can create an anonymous event handler using the Linq libraries and call your method that way. This can be a nice and quick way of doing something (especially if it's just a test project). But if you start using it extensively, it might become difficult to read it.

An example of this would be:

var menuItem1 = new MenuItem();
menuItem1.Click += (sender, e) => DoSomething();

Refer here for further information on using Linq: http://msdn.microsoft.com/library/bb308959.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM