I am writing a C# application and before I exit, I need to close another console application based on its window title... this second application (staticEngineWriter) is a C program that uses SetConsoleTitle() function to set its title.
The code I have in C# to do this is below. The problem is it is returning the process name instead of the window title of the C application. Seems simple enough but I wonder if it has to do with how the writer application is setting its title using the SetConsoleTitle function.
static void stopWriter()
{
Process[] proc = Process.GetProcessesByName("staticEngineWriter");
foreach (System.Diagnostics.Process CurrentProcess in proc)
{
Console.Writeline(CurrentProcess.MainWindowTitle); //debug
if (CurrentProcess.MainWindowTitle.Contains("My Writer"))
{
CurrentProcess.Kill();
}
}
}
Related
I have 4 applications and I have to use 4 different autohotkey exe applications for always on Top future. However, I would like to close all of them or kill their process.
I tried using ESC::ExitApp, Process.Kill() function as well, but only one of them is closing.
Here is my code:
#SingleInstance Force
WinSet, AlwaysOnTop, Toggle, Bot
Winset, Style, -0xC00000, Bot
^!p::Pause
*ESC::ExitApp
return
Other applications are the same but different Windows Title name.
Process[] bottom = Process.GetProcessesByName("bottom");
//MessageBox.Show(workers.Length.ToString());
foreach (Process bot in bottom)
{
bot.Kill();
bot.WaitForExit();
bot.Dispose();
}
Process[] left = Process.GetProcessesByName("left");
//MessageBox.Show(workers.Length.ToString());
foreach (Process l in left)
{
l.Kill();
l.WaitForExit();
l.Dispose();
}
Process[] right = Process.GetProcessesByName("test1");
//MessageBox.Show(workers.Length.ToString());
foreach (Process r in right)
{
r.Kill();
r.WaitForExit();
r.Dispose();
}
Process[] top = Process.GetProcessesByName("top");
//MessageBox.Show(workers.Length.ToString());
foreach (Process t in top)
{
t.Kill();
t.WaitForExit();
t.Dispose();
}
SendKeys.Send("{ESC}");
According to above code, I tried to kill 4 apps but only one is closing. Plus I cannot see in TaskManager running autohotkeys.exe files.Is there any way
to turn off or close all autohotkeys.exe files? Thank you in advance.
You can use the WMI from windows to do that.
ESC::
Query := "Select ProcessId, CommandLine from Win32_Process where name = 'Autohotkey.exe'"
for process in ComObjGet("winmgmts:").ExecQuery(Query, "WQL")
process, close, % process.ProcessId
Return
I have one console application for testing purposes like following:
static void Main(string[] args)
{
do
{
for (int i = 0; i < 10000000; i++)
{
Console.WriteLine("Doing some endless loop");
Console.WriteLine(i.ToString());
}
} while (true);
}
As you can see the code is very basic, and I've set it up to endless loop in order to test what I would like to achieve.
The other console application is called "Updater" and I would like to to pause the "EndlessLoop" console application once the "Updater" application is started.
Does anyone knows if this is doable in c# .NET?
public static bool IsAppRunning()
{
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName.Contains("Updater"))
{
return true;
}
}
return false;
}
If you call this in while loop it tells you if Updater is running or not.
Not easy to communicate between 2 application
One proposition: When your console Updater starts, you create a file in folder C:\Temps\token.txt. Then, if your console EndlessLoop detects a file names token.txt in C:\Temps, you pause EndlessLoop
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();
}
}
}
}
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();
}
}
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%.