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?
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
}