Windows auto activate method - c#

I need a windows activate method. My code works, but it create a popup window and I don't want it.
Is there any way to activate in background without any message?
private void tryingActivateWindows()
{
ProcessStartInfo psi = new ProcessStartInfo("cmd", "/c " + "SLMGR -ato");
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process p = new Process();
p.StartInfo = psi;
p.Start();
p.WaitForExit();
}

private void tryingActivateWindows()
{
Process activateScript = new Process();
activateScript.StartInfo.FileName = #"cscript";
activateScript.StartInfo.WorkingDirectory = #"C:\Windows\System32\";
activateScript.StartInfo.Arguments = "//B //Nologo slmgr.vbs -ato";
activateScript.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
activateScript.Start();
activateScript.WaitForExit();
}

Run "cscript C:\Windows\System32\slmgr.vbs /ato"
It will prevent the pop-up.

Related

System.InvalidOperationException: 'No process is associated with this object.'

public static void Process(string state)
{
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = Global.filepath + #"\PhoenixMiner.exe";
startInfo.Arguments = Global.command;
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo = startInfo;
if (state == "start")
{
p.Start();
}
else
{
Thread.Sleep(2000);
p.Kill(); //Error happens here
}
}
How can I kill the process correctly?
I tried some methods that were given in other answers but none seem to work.
You need to store a reference to the process in between clicks.
private static Process p = null;
public static void Process(string state)
{
if (state == "start" && p == null)
{
p = new Process();
p.StartInfo.FileName = Global.filepath + #"\PhoenixMiner.exe";
p.StartInfo.Arguments = Global.command;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
}
if (state != "start" && p != null)
{
p.Kill();
p.Dispose();
p = null;
}
}
The error is likely because you are trying to kill a Process which is not yet started, as per your if-else case.
public static void InitProcess()
{
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = Global.filepath + #"\PhoenixMiner.exe";
startInfo.Arguments = Global.command;
startInfo.CreateNoWindow = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo = startInfo;
p.Start();
Thread.Sleep(2000);
p.kill();
}
If you want to kill the process on condition basis, better to move the process kill block (else block in your case) to separate method and check the running process before you invoke kill.
Process[] runingProcess= Process.GetProcesses();
Also, have a look at overloaded method Process.Kill(false) here

Problem with running batch files from within my application

I've been trying to create a simple application to backup my Windows Server databases aswell as a whole server backup.
For this I want to use batch files which are being executed by my application.
I tried several approaches but for some reason it always fails so I'd be happy if you could help me out.
Batch file BACKUPSERVER:
wbadmin start backup -backupTarget:D: -include:C: -allCritical -quiet
I have to run the bat as administrator or it fails due to missing permissions.
C# code:
static Task<int> RunProcessAsync(string fileName)
{
............
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.Verb = "runas";
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C \"D:\\SQLBACKUP\\BACKUPSERVER.bat\"";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
Debugging says 'wbadmin wasnt found'. 'runas' activated or not doesn't make any difference.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fileName;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = true;
startInfo.CreateNoWindow = false;
// startInfo.Verb = "runas";
var process = new Process
{
StartInfo = { FileName = fileName },
EnableRaisingEvents = true
};
process.StartInfo = startInfo;
process.Exited += (sender, args) =>
{
tcs.SetResult(process.ExitCode);
process.Dispose();
};
process.Start();
Also doesn't work.
Any ideas?
EDIT:
I'm able to run commands like shutdown but wbadmin doesn't work whatsoever...
This is how I solved the problem:
Make sure ure compiling for 64bit if u intend to use your application on 64bit system, otherwise it will redirect to different subfolders and wont find 'wbadmin.exe'.
Run wbadmin with ProcessStart or run a batch but without direct cmd input, so use this with filename = batch file or wbadmin with startInfo.Arguments:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fileName;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = true;
startInfo.CreateNoWindow = false;
// startInfo.Verb = "runas";
var process = new Process
{
StartInfo = { FileName = fileName },
EnableRaisingEvents = true
};
process.StartInfo = startInfo;
process.Exited += (sender, args) =>
{
tcs.SetResult(process.ExitCode);
process.Dispose();
};
process.Start();
Make sure u request administrator rights

Open bat file by c#, but it's closed immediately [duplicate]

I currently have a portion of code that creates a new Process and executes it from the shell.
Process p = new Process();
...
p.Start();
p.WaitForExit();
This keeps the window open while the process is running, which is great. However, I also want to keep the window open after it finishes to view potential messages. Is there a way to do this?
It is easier to just capture the output from both the StandardOutput and the StandardError, store each output in a StringBuilder and use that result when the process is finished.
var sb = new StringBuilder();
Process p = new Process();
// redirect the output
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
// hookup the eventhandlers to capture the data that is received
p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
p.ErrorDataReceived += (sender, args) => sb.AppendLine(args.Data);
// direct start
p.StartInfo.UseShellExecute=false;
p.Start();
// start our event pumps
p.BeginOutputReadLine();
p.BeginErrorReadLine();
// until we are done
p.WaitForExit();
// do whatever you need with the content of sb.ToString();
You can add extra formatting in the sb.AppendLine statement to distinguish between standard and error output, like so: sb.AppendLine("ERR: {0}", args.Data);
This will open the shell, start your executable and keep the shell window open when the process ends
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
p.StartInfo = psi;
p.Start();
p.WaitForExit();
or simply
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
Process p = Process.Start(psi);
if(p != null && !p.HasExited)
p.WaitForExit();
Be carefull espacially on switch /k, because in many examples is usually used /c.
CMD /K Run Command and then return to the CMD prompt.
CMD /C Run Command and then terminate
var p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/k yourmainprocess.exe";
p.Start();
p.WaitForExit();
Regarding: "Member Process.Start(ProcessStartInfo) cannot be accessed with an instance reference; qualify it with a type name instead"
This fixed the problem for me....
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
Process p = Process.Start(psi);
p.WaitForExit();

How to hide the Command Window using c#

Building a console app that will execute an exe file(pagesnap.exe). I would like to hide its window(pagesnap.exe) during execution. How is it done.
ProcessStartInfo Psi = new ProcessStartInfo("D:\\PsTools\\");
Psi.FileName = "D:\\PsTools\\psexec.exe";
Psi.Arguments = #"/C \\DESK123 D:\files\pagesnap.exe";
Psi.UseShellExecute = false;
Psi.RedirectStandardOutput = true;
Psi.RedirectStandardInput = true;
Psi.WindowStyle = ProcessWindowStyle.Hidden;
Psi.CreateNoWindow = true;
Process.Start(Psi).WaitForExit();
DESK123 is the local PC. Would later try this with remote PCs.
Things I have tried
Psi.Arguments = #"/C start /b psexec \\DESK123 D:\files\pagesnap.exe";
Psi.Arguments = #"/b psexec \\DESK123 D:\files\pagesnap.exe";
Psi.Arguments = #"/C psexec \\DESK123 /b D:\files\pagesnap.exe";
Psi.Arguments = #"/C psexec \\DESK123 D:\files\pagesnap.exe 2>&1 output.log";
Update: I have built pagesnap with Output type as a windows application instead of console. The cmd window doesn't come up, now. Seems this is the only way for me
Simply call the following function. Pass the argument as your command and your working directory
private string BatchCommand(string cmd, string mapD)
{
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmd);
procStartInfo.WorkingDirectory = mapD;
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process cmdProcess = new System.Diagnostics.Process();
cmdProcess.StartInfo = procStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine("ping www.google.com"); //Execute ping
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit.
cmdProcess.WaitForExit();
// Get the output into a string
return Batchresults;
}
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
Batchresults += Environment.NewLine + e.Data.ToString();
}
void cmd_Error(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
Batchresults += Environment.NewLine + e.Data.ToString();
}
}

Hide Console Window while using Process.StartInfo with diffent Username

I'm starting a Process using a special User, Domain and Password. Although I told C# to hide the console window it is shown.
Here my code:
Process process = new Process();
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.UserName = strUsername;
process.StartInfo.Domain = strDomain;
process.StartInfo.Password = secPassword;
process.StartInfo.FileName = "PsExec.exe";
process.StartInfo.Arguments = #"/accepteula -s \\" + strServername + #"program.exe";
process.Start();
process.WaitForExit();
I could find some hints in another forum:
If you call the Start(ProcessStartInfo) method with the
ProcessStartInfo..::.UserName and ProcessStartInfo..::.Password
properties set, the unmanaged CreateProcessWithLogonW function is
called, which starts the process in a new window even if the
CreateNoWindow property value is true or the WindowStyle property
value is Hidden.
Actually, I'm not really satisfied with this statement...
Thanks in advance.
Cheers
Alex
As i know there are workaround on this issue. You can launch hidden cmd with your params. Something like this:
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", String.Format("/accepteula -s \\{0}program.exe", strServername));
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process.Start(psi);
using (Process LMUTIL = new Process())
{
string arg1 ="argument"
LMUTIL.StartInfo.FileName = "program.exe";
LMUTIL.StartInfo.Arguments = arg1
LMUTIL.StartInfo.UseShellExecute = false;
LMUTIL.StartInfo.RedirectStandardOutput = true;
LMUTIL.StartInfo.CreateNoWindow = true;
LMUTIL.EnableRaisingEvents = true;
LMUTIL.OutputDataReceived += p_WriteData;
LMUTIL.Start();
LMUTIL.BeginOutputReadLine();
}
private void p_WriteData(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
Debug.WriteLine(e.Data.ToString());
}
}
I lifted this straight out of a project that does what you need. Subscribe to the p_WriteData event to capture what would appear in the command window.
After all, it is not possible to hide this psexec console window using the Process Class.
It's not necessary to use psexec. I used the WMI stuff instead:
ConnectionOptions remoteConnectionOptions = new ConnectionOptions();
remoteConnectionOptions.Impersonation = ImpersonationLevel.Impersonate;
remoteConnectionOptions.EnablePrivileges = true;
remoteConnectionOptions.Authentication = AuthenticationLevel.Packet;
remoteConnectionOptions.Username = strDomain + #"\" + strUsername;
remoteConnectionOptions.SecurePassword = secPassword;
ManagementScope scope = new ManagementScope(#"\\" + strServername + #"\root\CIMV2", remoteConnectionOptions); ManagementPath p = new ManagementPath("Win32_Process");
ManagementClass classInstance = new ManagementClass(scope, p, null); object[] theProcessToRun = { "myExecutable.exe" };
classInstance.InvokeMethod("Create", theProcessToRun);

Categories

Resources