0

I have produced some code to display each printer installed and online in a menu item. But I can not figure how to raise an event when the menu item is clicked. I removed the code where I obtain the printernames because thats not relevant now.

string printerName; // contains the first printer name, later contains 2nd printername. This is variable.

selectprinterNameMenuItem.DropDownItems.Add(printerName); // here do I add the new printer to the menu item.

normally you should be able to add an event to the menu item; but I create it by code, and I do not know the exact name. How can I detect when the menu item is clicked on?

2pietjuh2
  • 879
  • 2
  • 13
  • 29
  • What events do you see either in code completion that sound relevant, or, you could look in the designer at the events.. So, then you'll know what its called and how to use it. – BugFinder Sep 26 '12 at 07:40
  • Do you mean that you don't know the names of the printers to tell which has been clicked? You could store that alongside in a List (Or even just grab the names back out of the control) – HaemEternal Sep 26 '12 at 07:43

2 Answers2

1

The Add(String) method of ToolStripItemCollection returns the created ToolStripItem. You can add your event handler to this object:

string printerName; // contains the first printer name, later contains 2nd printername. This is variable.

ToolStripItem addedItem = selectprinterNameMenuItem.DropDownItems.Add(printerName); // here do I add the new printer to the menu item.
addedItem.Click += new EventHandler(printerName_Click); // here you register to the click event

EDIT (according to your comment):

You can tell the printer name that has been clicked using the sender argument passed to the event handler, i.e.:

    void printerName_Click(object sender, EventArgs e)
    {
        ToolStripItem item = (ToolStripItem)sender;
        string printerClicked = item.Text;

        // whatever you want based on the printerName
    }
Francesco Baruchelli
  • 7,320
  • 2
  • 32
  • 40
  • Thank you. This helped me out a bit. But this way it doesnt matter which printer you select. All will raise the same event, is there an easy way to prevent this? If not I'll just write some extra lines code to work around this problem – 2pietjuh2 Sep 26 '12 at 08:23
0

Than hook on ItemClicked of your selectprinterNameMenuItem.

selectprinterNameMenuItem.DropDownItemClicked += new ToolStripItemClickedEventHandler(xyz);

There figure out whic item caused the event to fire.

Robert
  • 2,407
  • 1
  • 24
  • 35