My program (call it main program) runs under system privilege, and I need to start new program (e.g. pdf reader, call it target program) under user privilege from it. I find this solution: How to start a new process without administrator privileges from a process with administrator privileges? Please check Eugene's answer. By this way, it uses explorer.exe as a bridge to invoke the target program so that the target can run under user privilege.
But I find one issue of it. Each time I run the program, it will invoke one explorer.exe process. And if I run it then kill/close it for multiple times, then multiple explorer.exe processes shown in Task Manager.
One idea to solve it is when I start the target program via new Process(), I can remember its process id and then when quit program I just kill it by its process id.
But my code does not work.
The arg path for StartProcess() is string "C:\\Windows\\System32\\notepad.exe"
public void StartProcess(string path)
{
newProc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = path,
UseShellExecute = true,
Verb = "runas",
WindowStyle = ProcessWindowStyle.Normal
}
};
_ = newProc.Start();
Debug.WriteLine($"start my process (id = {newProc.Id})");
}
private void KillProcess(Process p)
{
if (!p.HasExited)
{
p.Kill();
Debug.WriteLine($"kill my process (id = {p.Id})");
}
else
{
Debug.WriteLine($"my process had quit already (id = {p.Id})");
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
KillProcess(newProc);
ShowExistingProcess();
}
You may find my demo project from GitHub: https://github.com/tomxue/KillExplorerDemo.git