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);
}
Related
This question already has answers here:
How do I determine the owner of a process in C#?
(10 answers)
Closed 13 days ago.
I have a C# program and I want only kill one specific process of it for example I have these three instance running at the same time in this way:
first application1 use the name.exe
2nd application2 use the name.exe
3rd application3 use the name.exe
when I am close the application1 I used the code for kill the process
Process[] pr = Process.GetProcessesByName("MAPPOINT");
foreach (Process prs in pr)
{
if (prs.ProcessName.ToUpper() == "NAME")
{
prs.Kill();
}
this code kill all name.exe process where I want to kill specific one.
how to kill only one process which is user by application1 not close the application2 and application3 process?
First to Start
If 'application1.exe' is always the first to start, then you could try killing the lowest PID. I believe PIDs are always assigned sequentially, so the lowest number would be the first that was opened.
So something like:
Process[] pr = Process.GetProcessesByName("MAPPOINT");
// check edgecase - no application open with this name...
if (pr.Length < 0) { return; }
//edgecase - give a default value
int firstPID= pr[0].Id;
//iterate through to find lowest number PID
foreach(Process prs in pr)
{
if (prs.Id < firstPID)
{
firstPID= prs.Id;
}
}
// close the first (aka lowest) PID
Process process = Process.GetProcessById(firstPID);
process.Kill();
If you need to be careful and only close if there are 3 or more application instances running, then put it in a function and check the length:
private static void CloseFirstInstance_IfMoreThanThree()
{
Process[] pr = Process.GetProcessesByName("MAPPOINT");
// check edgecase - no application open with this name...
if (pr.Length < 0) { return; }
//edgecase - not enough applicaitons open
if (pr.Length < 3) { return; }
//edgecase - give a default value
int firstPID = pr[0].Id;
...
}
Alternates
If the instance you want to kill is not the first to start, you may need to get fancy and:
Ask the user to select the window, then grab the pointer to the window, then grab the PID. (Getting more difficult - UI windows have been a pain for me.)
Actually might be simpler: you might try PID = Process.GetProcessesByName(MyProcessName).FirstOrDefault().Id; and kill that process. This could be all you need.
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.
From a C# service, how I can check whether another app is dead or not?
I tried to use Process.Responding, it returns true but the app is died.
This is the code:
private List<string> getListStringGAppPath()
{
List<string> listGAppPaths = new List<string>();
Process[] processes = Process.GetProcessesByName("MyApp");
if (processes.Length > 0)
{
for (int i = 0; i < processes.Length; i++) {
listGAppPaths.Add(processes[i].Responding.ToString() + "######" + processes[i].MainModule.FileName);
//processes[i].Responding.ToString() always return True
}
return listGAppPaths;
}
else
{
return null;
}
}
When process dies, windows seems to toggles its state to Suspended, you can try checking its state first. Also here: Detecting process crash in .NET
You can check if the process is responding:
foreach (var process in System.Diagnostics.Process.GetProcesses())
{
Console.WriteLine("Process Name: {0}, Responding: {1}", process.ProcessName, process.Responding);
}
Similar to this answer:
Check status of process
You can use the methods in System.Diagnostics.Process to get process information.
GetProcessesByName(String)
Creates an array of new Process components and associates them with all the process resources on the local computer that share the specified process name.
GetProcessById(Int32)
Returns a new Process component, given the identifier of a process on the local computer.
GetProcesses()
Creates a new Process component for each process resource on the local computer.
If the process does not exist, then it must have died?
I made a program that opens COM6. The program starts when the user logs on.
If another user logs on, while the first user is still logged in, the program crazes because the COM is already open.
I found this code, which I thought could solve the problem. The code was meant to close all other application with the same name, but apparently, it does not work, when the other app is running under another user. Have anybody got any solution for this ?
void CloseAllButMe()
{
Process[] processes;
Process self = Process.GetCurrentProcess();
processes = Process.GetProcessesByName(self.ProcessName);
foreach (Process p in processes)
{
if (self.Id != p.Id) p.CloseMainWindow();
}
}
You can use the methods Process.Kill to stop a process. Calling Kill will immediately stop the process and could cause a loss of work.
Here is a code sample for killing Calculator:
public static void KillPaint()
{
System.Diagnostics.Process[] procs = null;
try
{
procs = Process.GetProcessesByName("calc");
Process mspaintProc = procs[0];
if (!mspaintProc.HasExited)
{
mspaintProc.Kill();
}
}
finally
{
if (procs != null)
{
foreach (Process p in procs)
{
p.Dispose();
}
}
}
}
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%.