Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,The project I wrote takes time when processing.I want the user to be able to cancle the process by clicking a button.How can I do that? Thanks in advanve.
Posted

C#
try{ 
     Process proc = Process.GetProcessesByName("Processname");
      proc.Kill();
}catch (Exception ex)
{      MessageBox.Show(ex.Message.ToString());
}
 
Share this answer
 
v2
You can also use
C#
private void Buttoncancel_Click(object sender, System.EventArgs e)
{
   System.Diagnostics.Process[] myProcesses;
   myProcesses =
      System.Diagnostics.Process.GetProcessesByName("ProcessName");
   foreach (System.Diagnostics.Process instance in myProcesses)
   {
      instance.CloseMainWindow();
   }
}
 
Share this answer
 
It depends on how you are doing it.
If you have the long operation running in the UI thread (ie, you haven't moved it to a separate thread already) then it will block the user interface from doing anything - so it can't respond to you mouse clicks or button presses. There is a way round that, by calling Application.DoEvents, but it is a very nasty solution, and can make response sluggish if you don't call it often enough, or make the processing much much longer if you call it too often.

A much better solution is to put the long operation in a separate thread - look at the BackgroundWorker class[^] - it's pretty simple, and the link includes a sample with a cancel button.

If you already have it if a separate task, then just cancel the operation!
 
Share this answer
 
Comments
RaviRanjanKr 2-Jan-12 15:03pm    
My 5+
Have a look at the BackgroundWorker Class[^]. You could execute your logic using the background worker and offer the user a possibility to cancel the execution by calling CancelAsync [^] in the button.
 
Share this answer
 
Comments
RaviRanjanKr 2-Jan-12 15:03pm    
My 5+
Wendelius 3-Jan-12 0:28am    
Thank you Ravi :)
Sergey Alexandrovich Kryukov 2-Jan-12 22:58pm    
Certainly one way of doing it, a 5.
--SA
Wendelius 3-Jan-12 0:28am    
Thank you SA :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900