//check if right button
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
//get service name
ServiceName = listViewObject.GetItemAt(e.X, e.Y).Text;
//set list view item
ServiceItem = listViewObject.GetItemAt(e.X,e.Y);
//create popup menu
listViewObject.ContextMenu = mnuContextMenu;
try
{
//get specific service object
queryCollection = getServiceCollection("SELECT * FROM Win32_Service Where Name = ''" +
ServiceName + "''");
foreach ( ManagementObject mo in queryCollection)
{
//create menu depending on service state
if (mo["Started"].Equals(true))
{
menuItem.Text = "Stop";
//set action property
ServiceAction = "StopService";
}
else
{
menuItem.Text = "Start";
ServiceAction = "StartService";
}
mnuContextMenu.MenuItems.Add(menuItem);
// Add functionality to the menu items using the Click event.
menuItem.Click += new System.EventHandler(this.menuItem_Click);
}
}
catch (Exception e1)
{
MessageBox.Show("Error: " + e1);
}
}
}
/// <summary>
/// List view context menu click event to invoke start/stop service
/// </summary>
///
///
private void menuItem_Click(object sender, System.EventArgs e)
{
ManagementObjectCollection queryCollection;
ListViewItem lvItem;
//Set up a handler for the asynchronous callback
ManagementOperationObserver observer = new ManagementOperationObserver();
completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler();
observer.ObjectReady += new ObjectReadyEventHandler(completionHandlerObj.Done);
//get specific service object
queryCollection = getServiceCollection("Select * from Win32_Service Where Name =''" +
ServiceName + "''");
//Status
updateStatus("Starting/Stopping service");
foreach ( ManagementObject mo in queryCollection)
{
//start or stop service
mo.InvokeMethod(observer, ServiceAction, null);
}
//wait until invoke method is complete or 5 sec timeout
int intCount = 0;
while
(!completionHandlerObj.IsComplete)
{
if
(intCount > 10)
{
MessageBox.Show("Terminate process timed out.", "Terminate Process Status");
break;
}
//wait 1/2 sec.
System.Threading.Thread.Sleep(500);
//increment counter
intCount++;
}
//see if call was successful.
if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0")
{
//succeeded
lvItem = ServiceItem;
if (ServiceAction == "StartService")
lvItem.SubItems.Text = "Started";
else
lvItem.SubItems.Text = "Stop";
}
else
{
//error message
string stringAction;
if (ServiceAction == "StartService"