-4

i was wrote some codes, when my apps still run, it will close another (example notepad) even the notepad is reopen it will close again, i've try some, but it will close when my apps startup , when my apps is running, and i open notepad, notepad wont close. here

foreach (Process Proc in Process.GetProcesses())
            if (Proc.ProcessName.Equals("notepad"))
                Proc.Kill();
oebanez
  • 59
  • 2
  • 6
  • 2
    Perhaps the process isn't called notepad? What debugging did you do? – David Heffernan Feb 09 '14 at 16:53
  • it work if i run notepad first n then i run my apss, but if i run my apps first then i run notepad it doesnt work – oebanez Feb 09 '14 at 16:54
  • 1
    Depending on where this `foreach` loop is located in your program, it will only run one time. You need to post a better explanation of your problem. Specifically "What is the exact problem you are having", "What are you trying to accomplish" and finally, please post the code *around* this `foreach` so we can see how it is being called. – Evan L Feb 09 '14 at 16:55
  • 2
    How often do you run this code then? If you run this code before Notepad opens, and never again, of course it won't kill Notepad. – krillgar Feb 09 '14 at 16:55
  • @oebanez the reason it doesn't work after you run the application is because the code that kills the process has already been executed. – Evan L Feb 09 '14 at 16:55
  • I think a big question is, "Why do you want to keep notepad closed?". What happens if I'm using notepad to keep an important block of text that I want to copy into a Word document or something? I won't use your program if it keeps erasing my stuff. – krillgar Feb 09 '14 at 16:57
  • 1
    @krillgar i would bet that he is trying to suppress some *other undisclosed super secret* program, and just using Notepad as an example. – Evan L Feb 09 '14 at 16:57
  • @Evan L can u show me the true one for my case – oebanez Feb 09 '14 at 16:57
  • 1
    @oebanez the "True One" is you need to find a way to run the method on a timer or some other recurring basis. Not going to write your code for you. – Evan L Feb 09 '14 at 16:59
  • Or if you hate notepad so much, you could just delete it ;) – Evan L Feb 09 '14 at 17:01

1 Answers1

3

Your code kills processes that are running at the time you code executes. Once your code has finished executing it no longer exerts any influence. It won't kill processes that are started after your code has finished executing.

Probably you need to detect when the target process starts, and then kill it. You can do that by polling which is rather inelegant. To avoid polling you need WMI. There are many examples of how to do this. For instance: How to detect a process start & end using c# in windows?

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490