Restart other application. C#, .net - c#

I want to restart some process. Lets call it someApp.exe.
How can I restart that process? It's not my application. It's some external program.

What you want to do is:
Kill the process
Start it again
There are some ways of obtaining a Process instance in C#. Let's suppose you know the name of the process:
var process = Process.GetProcessesByName("notepad++")[0];
Then you can do:
process.Kill();
But to start it again, you need to know the path of the process, so before killing it, save the path of the executable:
var path = process.MainModule.FileName;
And then you can do:
Process.Start(path);
You should check if GetProcessesByName returns elements before taking the first element, but I just wanted to focus on the important thing here.

You can use the Process.Start.
http://msdn.microsoft.com/en-us/library/53ezey2s.aspx#Y1400

Related

Is there a way to kill a process automatically by filtering its name?

I have a process in my Task Manager, which is end-able, but keeps starting up again.
No Anti Virus has found this ad-ware virus yet, and I'm starting to think the only way to stop it from opening is to filter out its name in a program.
This is a very brief example of what I want
If process.XXX Alive = True;
{
Get process.XXX.PID;
PID.End();
}
Please ask me for any additional information.
Edit: Changed 'id' to 'pid'
// Sub adware with the name of the process
// Do not include .exe in the process name
Process p[] = Process.GetProcessesByName("adware");
foreach(Process pr in p) pr.Kill();
Internally Task Manager uses the Windows Management API. From the command line you can kill processes by name, using the built-in wmic windows management console program.
For example, this will kill all instances of notepad:
wmic process where "name like '%notepad%'" call terminate
It can do other things too:
wmic process where "name like '%notepad%'" get executablepath
Then you can find that file and delete it.
Note: To kill processes not owned by you, you must use an elevated command prompt.
Note 2: You don't say what the process is, so there is a danger that I am helping you destroy your system without realising it. Before doing this, find out what the executable path and command line are, and investigate whether they are actually problem software.
wmic process where "name like '%program%'" get executablepath,commandline

How to get list of installed program on Windows and being able to kill some of them

So i'm trying to write a program that will list all the installed programs on Windows and let user decided which one to be blocked(Killed).
I found the solution of List Installed program here. Get installed applications in a system
And to kill a program you just need the .exe name and kill all the process with that name.
But my problem is the names in the list of installed program is not necccesary the .exe name, and you couldn't find a process without the .exe name. For example, the installed program name is "Google Chrome" but the .exe or the process name would be chrome.
The current solution I can think of is to find out the installed directory of the installed program, find all the .exe files under it. And kill all of them if required. But I don't know how to get the directory of all the installed programs.
So, I can't help wonder, is there a more elegant of doing it. Any suggestions would be appreciated.
You have to split this question on 2 parts:
1. Find all the programs
What does it mean? It means that You want to find all the executable files (*.exe) on the hard drive of the client. This executable files does include the code which will run in the memory and do some work.
BUT: The code located on harddisk cannot be "killed", as the code (exe file) will start first new instance of application (via OS interface). Once You got the instance we can start talking about other part of question.
Also as stated there, You are unable to get easily 1 exe file, as multiple application might have multiple exe files. And if You really want to have them, You got to run analysis on the harddisk, like there:
var allExePaths =
from drive in Environment.GetLogicalDrives()
from exePath in Directory.GetFiles(drive, "*.exe", SearchOption.AllDirectories)
select exePath;
Also as Ivar stated in comments, there are multiple executables, like *.jar, *.pyc, ... which might be run via other executable file.
2. Kill the required program
If You want to kill some program/application, You need to get it's instance. Instance are distinguished by PID (process ID). Once You got this of the instance, You can kill it. Answer for this is there: How do I kill a process using Vb.NET or C#?
The code below will take all process with particular name and kill them all.
Code:
foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") )
{
try
{
p.Kill();
p.WaitForExit(); // possibly with a timeout
}
catch ( Win32Exception winException )
{
// process was terminating or can't be terminated - deal with it
}
catch ( InvalidOperationException invalidException )
{
// process has already exited - might be able to let this one go
}
}

Is it possible to construct a ProcessStartInfo from an already running process?

If I connect to a running process by extracting it using Process.GetProcessesByName("Notepad");, is it possible to reconstruct that processĀ“s ProcessStartInfo?
I would for example want to be able to attach to Notepad, Kill it and Start it again. Without a valid ProcessStartInfo the Start call will fail.
There is no direct support for this.
You can go over each property of the running process and initialize a ProcessStartInfo object with the corresponding values.
No, there are cases where that's not possible. A simple example is:
Process.Start("example.lnk");
No way to find out later that a .lnk file was used to get the process started.
The WorkingDirectory is a tricky one, a process often requires it to be set correctly but might change it later. A process that got started with a different user account is insurmountable, no way you can provide the correct account password. A custom environment is yet another one.

C#: Restrict how a console app can be called

We have a product that is a C# console app. Is it possible to restrict it to run from the command line only? In other words, users wouldn't be able to call it from a script or another app.
If it is, some example code would be much appreciated. Thanks.
You can check the process that created your application using the code given here: http://msdn.microsoft.com/en-us/netframework/aa569609.aspx#Question3 . To be started at the DOS command line the parent process should be cmd.exe. Note however as pointed out by Colin this can be bypassed easily using a batch script. You can disable that as well by making sure that the command prompt arguments to cmd.exe are null. For this you will need to use WMI :
http://skysanders.net/subtext/archive/2010/04/11/using-wmi-to-fetch-the-command-line-that-started-all.aspx
You should also check the cmd.exe image is from system32 folder.
I don't think it is possible to tell the difference.
Certainly the parent process is not a useful indicator. This is what you get in the parent process:
1. type app name into Command Prompt: cmd.exe
2. call app from batch script: cmd.exe
3. Double click on app or shortcut: explorer.exe
4. type app name into Run dialog box: explorer.exe
If you intend for 1. to be a valid way to start your program, then I don't think you can stop 2. which means your app can be called from any script or any program (since it's simple for another program to create a 1 line batch script and execute it)
(BTW, does anyone know a way to get a table on StackOverflow?)
#swisston if you start your console application from your another own application, than i want to recommend you "named kernel objects". For example mutex. You can create named mutex in your parent app. Then in main thread of your child console app try to open this mutex. If mutex not opened (not found): console app has no permissions to continue and must be closed;) wait, i'll make some code for you;)
Edit:
So it is very easy tactics. In parent app create your named mutex:
Mutex mutex = new Mutex(true, "MyPermissions");
Then in your child console application check if your mutex exists:
static bool CheckPermissions()
{
try
{
Mutex mutex = Mutex.OpenExisting("MyPermissions");
}
catch (Exception ex)
{
return false;
}
return true;
}
If your console application was run without your parent application CheckPermissions method will return false and console must be closed;)
I don't agree with what you're trying to do, but here is an idea that could work: require some sort of user input at the beginning of the program, maybe some sort of CAPTCHA (difficult to do in command line, but theoretically possible. Think ASCII art).

Kill process started with System.Diagnostic.Process.Start("FileName")

I am trying to create an app that will perform actions on specific times (much like the Windows Task Scheduler). I am currently using Process.Start() to launch the file (or exe) required by the task.
I am initiating a process by calling a file (an .mp3) and the process starts WMP (since it is the default application). So far so good. Now I want to kill that process. I know that it is normal behavior for the Process.Start(string, string) to return nothing (null in C#) in this case.
So I am asking how can I close WMP when I called it through Process.Start(string, string)??
Edit:
Please note that I am not opening WMP directly with Process.Start() and this is the line with which I run the process:
VB: Me._procs.Add(Process.Start(Me._procInfo))
C#: this._procs.Add(Process.Start(this._procInfo))
_procInfo is a ProcessStartInfo instance. _procInfo.FileName is "C:\route\myFile.mp3". That is why WMP opens. In any case, all of the Start() methods, except for the instance-one which returns a boolean, return nothing (null in C#), because WMP is not the process that was directly created (please note that WMP is run and the song does play).
Process.Start(string,string) returns you a Process resource that you can use to further control the new process.
Process newProcess = Process.Start("param1", "param2");
if (newProcess != null && !newProcess.HasExited)
newProcess.Kill();
The same structure works if you use Process.Start(string), or any other static Process.Start overload.
Process.Start() is a member function and associates a new or reused Process with the Process component identified by this. Behaviour of this method depends on the properties of the Process identified by this.
Don't do it this way.
It's not clear whether the intent of your program is 'Always launch with Windows Media Player' or 'Launch with the registered MP3 player', which might be, say, iTunes.
If you need WMP, use Process.Start with the full path to windows media player.
If you need the registed MP3 player, you can find out the correct exe using the code shown here. Again, start the process with this exe path, passing the MP3 as a parameter.
Two ways:
1-
Process customProc = Process.Start("ExecutablePath", "Argument(s)");
customProc.Kill()
2-
Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("ProcessName")
For Each p As Process In pProcess
p.Kill()
Next
If you are letting the registered windows program to open the file, rather than picking the program you want. Then I advise you do not kill the process.
The reason for this is what say your program does use the default application, but that application is already in use, and contains unsaved data. A user would not be happy for your program to overtake there application with the new file and then kill off the process that was already in use by the user for another purpose. Sure, it might not be in use but you must consider the worst case.
As such, I recommend what has been suggested. use Process.Start() with the full path to the program to be used and the file to be opened.
I tried to open .txt file and the process of my text editor was returned, also I tried .mp3 by WMP and it returned null. So it depends on the application. Do you need to run you mp3 only with WMP? If not, you definitely can create the application which will return the Process object.
proc = Process.Start(filename) should work, but like you say, it returns null instead of a process.
That seems to be inherent to Windows Media Player. Other applications return the process. You can get Windows Media Player's process by specifying the application in the start method.
proc = Process.Start("C:\Program Files\Windows Media Player\wmplayer.exe", filename)
Then you can kill it normally.
proc.Kill()
You will probably need to get the location of the application assiciated with .mp3 files from the registry.

Categories

Resources