0

I wrote this code:

Process Processs = Process.GetProcessesByName("ProcessName")[0];
        
do
{
    await Task.Delay(1500);
}
while (!(Processs.MainWindowHandle != IntPtr.Zero));

// stuff to do here
Processs = (Process)null;

But I get an error

index was outside the bounds of the array

Can anyone help me fix it? Or write new, better code?

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
esus
  • 5
  • 4
  • 3
    it seems that `Process.GetProcessesByName("ProcessName")` is returning 0 processes, i.e. the process you are looking for is not running. By the way, avoid to name a local variable as a class: `Process process` or `Process proc` or something similar is going to be much more readable – Gian Paolo May 25 '22 at 04:53
  • Also, no need for this `Processs = (Process)null;` (and no need for the cast as well, you can assign `null` without casting) – Gian Paolo May 25 '22 at 04:55
  • How Do I Prepare about return 0 process? – esus May 25 '22 at 04:59
  • Well, `Process.GetProcessesByName("ProcessName")` returns a `Process[]` array, so you could check if its length is > 0. – DiplomacyNotWar May 25 '22 at 05:26
  • Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – knittl May 25 '22 at 05:42
  • nope not working – esus May 25 '22 at 05:55
  • I got 'Process' is a type, which is not valid in the given context – esus May 25 '22 at 06:54

1 Answers1

0

Process.GetProcessesByName is returning array type object. So, we can check length of the process

Process[] processes = Process.GetProcessesByName("ProcessName");
    if(processes.length >0){
        // task is running 
    
    }
    else {
       // task is not running 
    
    }
knittl
  • 216,605
  • 51
  • 293
  • 340
Ajay Gupta
  • 319
  • 2
  • 8