Veriditas
Veriditas

Reputation: 113

Different process handles

I'm trying to check, when the program starts, if an instance is ever launch. If it is, I whould like to kill it.

I've this code:

        Process[] processes =
            Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location));

        while (processes.Length != 0)
        {
            bool killed = false;

            foreach (Process process in processes)
            {
                string fileName;

                try
                {
                    fileName = process.Modules[0].FileName;
                }
                catch (Win32Exception)
                {
                    continue;
                }

                if ((fileName == Assembly.GetExecutingAssembly().Location)
                    && (process.Handle != Process.GetCurrentProcess().Handle))
                {
                    MessageBox.Show("Test");

                    process.Kill();
                    Thread.Sleep(500);

                    killed = true;
                    MessageBox.Show("Test");

                }
            }

            if (!killed)
                break;

            processes =
                Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location));
        }

The only problem is that when I compare the 2 processes handle, when the process checked is my program instance, the handles are different.

Upvotes: 0

Views: 125

Answers (1)

qbik
qbik

Reputation: 5938

Compare the processes by Id instead of Handle.

Upvotes: 2

Related Questions