Home >Backend Development >C++ >How Can I Determine if a Specific Process is Running in C#?

How Can I Determine if a Specific Process is Running in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-15 21:22:43534browse

How Can I Determine if a Specific Process is Running in C#?

Check the process running status

The Process class in the System.Diagnostics namespace represents a running process. It provides a variety of process operation methods, including querying process status. When accessing a Process reference, it is critical to determine whether it is running.

Use ProcessName method

One way to check the status of a process is to use the GetProcessesByName method:

<code class="language-csharp">Process[] pname = Process.GetProcessesByName("notepad");
if (pname.Length == 0)
  MessageBox.Show("未运行");
else
  MessageBox.Show("正在运行");</code>

This code retrieves all processes with a specified name (e.g., "notepad"). If the length of the result array is zero, it means that no process of that name is running; otherwise, it means that there is currently a process running.

Traverse the process

Another way is to loop through all running processes and check their IDs:

<code class="language-csharp">Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist){
   Console.WriteLine("进程:{0},ID:{1}", theprocess.ProcessName, theprocess.Id);
}</code>

This method iterates over all active processes, displaying their names and IDs. It provides a more comprehensive view of running system processes.

The above is the detailed content of How Can I Determine if a Specific Process is Running in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn