How can I get process Id from process name? (C#) - c#

How can I get process id from process name on C#?
I got processes using Process.GetProcessesByName("notepad");
But how can I get process id from this?

That returns an array.. because you could have 1, 4, 5 or 10 notepads open at the same time.
So, you could list them like this:
var processes = Process.GetProcessesByName("notepad");
foreach(var p in processes)
{
Console.WriteLine($"Notepad process found with ID: {p.Id}");
}

// To get NOTEPAD.EXE processes
var processes = Process.GetProcessesByName("notepad");
foreach (var process in processes)
{
Console.WriteLine("PID={0}", process.Id);
Console.WriteLine("Process Handle={0}", process.Handle);
}
Code taken from here.

Related

List of process children in C#

In C# I am trying to get names of all opened windows, so I check processes and display their names.
I have a problem because child processes are not included, how can I include to also child processes not only one?
This is used now:
Process[] processes = Process.GetProcesses();
foreach (Process p in processes)
{
if (!String.IsNullOrEmpty(p.MainWindowTitle))
{
MessageBox.Show(p.MainWindowTitle);
}
}

Processes: receiving current open

I want to troll my brother a Little bit ;) by writing a program, which I can put in his "StartUp"-Folder. This program should scan his default system tasks so that it doesn't destroy his computer so I wrote all currently open processes in a list. Now I want to check when he opens a program (Process) is it in the list("Taskmgr" is also in the list, so you can exit the troll anytime)? If the opened Process is not in the list, kill it. If you Need any further information, please ask...
My current code is this:
void CloseProcesses()
{
Process[] arrProcesses = Process.GetProcesses();
List<string> lststrProcessNames = new List<string>();
/*Writes current running processes(+ taskmanager process) in a list*/
foreach (Process CurrentProcess in arrProcesses)
{
lststrProcessNames.Add(CurrentProcess.ProcessName);
}
lststrProcessNames.Add("taskmgr");
try
{
Process[] arrNewProcesses = Process.GetProcesses();
foreach (Process NewCurrentProcess in arrNewProcesses)
{
if (lststrProcessNames.Contains(NewCurrentProcess.ProcessName))
{
CloseProcesses();
}
else
{
NewCurrentProcess.Kill();
}
}
}
catch
{
this.Close();
}
}

Kill process by part of name

Can please some one tell me how to kill a process by part of name? Example: I want to kill "explorer" but in code I want to implant to kill it by word "explor" and the rest should find out by code. Here is the code so far:
Process[] localByName = Process.GetProcessesByName("explorer");
foreach (Process p in localByName)
{
p.Kill();
}
Thank you
You could get all of the processes, then search afterwards:
var processes = Process.GetProcesses();
foreach(var p in processes.Where(proc => proc.ProcessName.IndexOf(searchString, StringComparison.CurrentCultureIgnoreCase) > -1))
p.Kill();
var localByName = Process.GetProcesses()
.Where(p => p.ProcessName.Contains("explor"));
foreach (Process p in localByName)
{
p.Kill();
}

Get all process of current active session

I have a small problem while developing an application. I want to access all process of the current session only. Currently I am using Process class but it will return all process of all session.
Please help me to get process of the current active session only not all.
Help needed to solve the problem.
This will give you a list of the process running that are running with the same sessionID as
the current process. I think that is what you want.
Process[] runningProcesses = Process.GetProcesses();
var currentSessionID = Process.GetCurrentProcess().SessionId;
Process[] sameAsThisSession =
runningProcesses.Where(p => p.SessionId == currentSessionID).ToArray();
foreach (var p in sameAsthisSession)
{
Trace.WriteLine(p.ProcessName);
}

Kill some processes by .exe file name

How can I kill some active processes by searching for their .exe filenames in C# .NET or C++?
Quick Answer:
foreach (var process in Process.GetProcessesByName("whatever"))
{
process.Kill();
}
(leave off .exe from process name)
My solution is to use Process.GetProcess() for listing all the processes.
By filtering them to contain the processes I want, I can then run Process.Kill() method to stop them:
var chromeDriverProcesses = Process.GetProcesses().
Where(pr => pr.ProcessName == "chromedriver"); // without '.exe'
foreach (var process in chromeDriverProcesses)
{
process.Kill();
}
Update:
In case if you want to do the same in an asynchronous way (using the C# 8 Async Enumerables), check this out:
const string processName = "chromedriver"; // without '.exe'
await Process.GetProcesses()
.Where(pr => pr.ProcessName == processName)
.ToAsyncEnumerable()
.ForEachAsync(p => p.Kill());
Note: using async methods doesn't always mean code will run faster.
The main benefit is that the foreground thread will be released while operating.
You can use Process.GetProcesses() to get the currently running processes, then Process.Kill() to kill a process.
If you have the process ID (PID) you can kill this process as follow:
Process processToKill = Process.GetProcessById(pid);
processToKill.Kill();
You can Kill a specific instance of MS Word.
foreach (var process in Process.GetProcessesByName("WINWORD"))
{
// Temp is a document which you need to kill.
if (process.MainWindowTitle.Contains("Temp"))
process.Kill();
}
Depending on how many processes there are to kill (e.g. when its hundreds like in my case), foreaching over all of them might take quite a while. (interesting sidenote: while Kill() was usually quite quick in .NET FW 4.8 , somehow in NET 6.0 Windows its a lot slower - seeing multiple Win32Exceptions in the debug/trace until the target process is finally done)
Anyway back to topic:
In case of an app shutdown, where u need to make sure every process is is gone, consider using the TAP library - particulary the Parallel shortcuts, hundreds of processes killed within a glimpse.
Usage example:
var procs = Process.GetProcessByName("mydirtyprocesses");
if (procs.Length == 0) return;
procs.AsParallel().ForAll(process =>
{
try
{
process.Kill();
// No process linked to the process comp (mostly because the process died in
// the short timespan between invoking GetProcess() and the effective
// initialization of the props/fields of the component. -OR- Process has
// already exited (when the exit happened after the process component has
// beenpopulated (difference is, in case 1 you cannot even get the Process
// ID from // the component, in case 2 you see data like Id and get the true
// for HasExited // - so always be prepared for that.
// catch (InvalidOperationException)
{
// Process is gone, no further action required
return;
}
// Ensuring process is gone (otherwise try again or fail or whatever)
if (!process.HasExited)
{
// Handle it
}
}
In this particular scenario just wrap it properly in try/catch , as with such a number of processes the probability for an exception is quite increased
static void Main()
{
string processName = Process.GetCurrentProcess().ProcessName;
int processId = Process.GetCurrentProcess().Id;
Process[] oProcesses = Process.GetProcessesByName(processName);
if (oProcesses.Length > 1)
{
if ((MessageBox.Show("Application is opened!", "",MessageBoxButtons.YesNo) == DialogResult.Yes)) ;
{
foreach (var process in Process.GetProcessesByName(processName))
{
if (process.Id != processId)
{
process.Kill();
}
}
}
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmLogin());
}
}
public void EndTask(string taskname)
{
string processName = taskname.Replace(".exe", "");
foreach (Process process in Process.GetProcessesByName(processName))
{
process.Kill();
}
}
//EndTask("notepad");
Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.

Categories