Processes: receiving current open - c#

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();
}
}

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);
}
}

Closing a program running under another users profile using C#

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();
}
}
}
}

C# how to get process from all sessions

I am running code on Windows Server 2012 R2 where i have multiple sessions.
On each session there is few Notepad.exe opened with different window name.
How i can get a list of all Notepad.exe processes from all sessions so i can minimize window or close process for selected process from a list ?
I used this code, but it gives me only processes from current session where i am logged in.
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (!string.IsNullOrEmpty(process.MainWindowTitle))
{
if (process.ProcessName == "notepad")
{
Console.WriteLine("Process: {0} - ID: {1} - Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
}
}
}
I solved my issue thanks to #Lex Li, used library from nuget.
I used this line if (process.ProcessName == "notepad.exe" && session.SessionId == process.SessionId) to extract only process name i need and match it to session.
using Cassia;
// call all process from sessions
private void GetSessionsProcess()
{
ITerminalServicesManager manager = new TerminalServicesManager();
ITerminalServer server = manager.GetLocalServer(); // server name
server.Open();
WriteProcesses(server.GetProcesses(), manager);
}
// get all process that is running in all sessions
private void WriteProcesses(IEnumerable<ITerminalServicesProcess> processes, ITerminalServicesManager manager)
{
ITerminalServer server = manager.GetLocalServer();
foreach (ITerminalServicesProcess process in processes)
{
foreach (ITerminalServicesSession session in server.GetSessions())
{
if (process.ProcessName == "notepad.exe" && session.SessionId == process.SessionId)
{
PopulateTerminalsList(process.SessionId.ToString(), process.ProcessId.ToString(), process.ProcessName, session.UserAccount.ToString(), session.UserName);
}
}
}
}

Check for open Windows application and wait until it is closed?

I have a pretty simple program where it runs certain steps. Each step should run pragmatically. I am having trouble with a bit of my code. Where I am relying on an application to close (waiting for user to close OUTLOOK ) to execute my next block of code. It launches the first file fine but it reads OUTLOOK as open then it wont work. I wish to make it that when the user closes outlook it will continue and open the next HTML file I have tried to Google for something like wait for exit on this line of code Process[] localByName = Process.GetProcessesByName("OUTLOOK");
but I couldnt find anything
static void Main(string[] args)
{
var myProcess = new Process { StartInfo = new ProcessStartInfo(#"c:\TestFile1.html") };
myProcess.Start();
//Launches the html file
Thread.Sleep(1000);
Process[] localByName = Process.GetProcessesByName("OUTLOOK");
//used for detecting whether outlook is open
if (localByName.Length == 0)
{
//Only runs when outlook is closed by user
var myProcess2 =
new Process { StartInfo = new ProcessStartInfo(#"c:\TESTFILE2.html") };
myProcess2.Start();
}
else
{
Console.WriteLine("Im not going to work " + localByName.Length);
Console.ReadLine();
}
}
You are searching for the Process.WaitForExit()Method ( https://msdn.microsoft.com/library/fb4aw7b8(v=vs.110).aspx)
You can use it like:
foreach(var process in localByName) {
if(!process.HasExited()) {
process.WaitForExit();
}
}

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