C# process start focus issue - c#

When I start a new process, it automatically gets the focus. how can I prevent it from getting the focus or instead get back the focus to my application?
here is the code I'm using:
string path = #"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
Process p = Process.Start(info);
I just need the executed process not to get the focus.
Thank you very much,
Adi Barda

Maybe setting the WindowStyle property to Minimized can help.

If you don't need to show the process at all, try this:
string path = #"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
info.WindowStyle = ProcessWindowStyle.Hidden;
Or set WindowStyle to ProcessWindowStyle.Minimized if you want it visible but minimized, as Uwe Keim said.

can you do
myForm.Focus();
where myForm is the form on your main application

What i´ve done was to wait a little delay until the other application was succesfully loaded, then focus my application window.
//Test window
const string strCmdText = "/C cd C:\\sqlcipher";
Process.Start("CMD.exe", strCmdText);
//Delay
int liMilliseconds = 50;
Thread.Sleep(liMilliseconds);
//Code to bring window to front
this.WindowState = FormWindowState.Minimized;
this.Show();
this.WindowState = FormWindowState.Normal;

Related

WPF ShowDialog in started process is not blocking main window of current process

I have window application that starts process with WPF window. I send current process ID to the starting process, so WPF window can set owner properly:
MainWindow mainWindow = new MainWindow();
int parentProcessId = int.Parse(e.Args[0]);
System.Diagnostics.Process parentProcess = System.Diagnostics.Process.GetProcessById(parentProcessId);
WindowInteropHelper helper = new WindowInteropHelper(mainWindow);
helper.Owner = parentProcess.MainWindowHandle;
mainWindow.ShowDialog();
Alt+Tab works as expected - WPF window blocks parent window. But it does not block parent widow's controls so I can push every button in parent window and even close it.
I'm starting new process like this:
string arguments = Process.GetCurrentProcess().Id.ToString();
ProcessStartInfo startInfo = new ProcessStartInfo(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "WPF.App.exe"), arguments);
Process.Start(startInfo);
How can I open WPF window so it blocks owner window's controls (and not only appears on top and blocks Alt+Tab)?
Thank you.
Assuming that the parent process is also a WPF app:
private void SomeMethod()
{
string arguments = Process.GetCurrentProcess().Id.ToString();
ProcessStartInfo startInfo = new ProcessStartInfo(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "WPF.App.exe"), arguments);
childProcess = Process.Start(startInfo);
childProcess.Exited += childProcess_Exited;
childProcessWaitFrame = new DispatcherFrame;
Dispatcher.PushFrame(childProcessWaitFrame);
}
private void childProcess_Exited(object sender, EventArgs e)
{
childProcessWaitFrame.Continue = false;
}

Reading Python/Command Prompt line output C#

I am trying to make a log using a C# windows form application. The goal here is to press a button to start a batch file (below) and get the text/data written to the command prompt, as it is written if possible, then send it to a listbox on my application. Think of it as a program for a server (which its not, its a discord bot.), my goal is just to have the "logs" sent to the application in real time.
Question: How can I create my own console inside my windows form application, example would be: If an echo said "Hello" I want it to display "Hello" in my listbox in realtime.
CMD File being Ran
#echo off
cd "C:\Users\gunzb\Desktop\Tarkov Bot\"
:loop
py bot.py
SET /A time=3
:timer
timeout /t 1 /nobreak>nul
echo Restarting in %time%
SET /A time-=1
IF %time% EQU 0 (goto skiploop) ELSE (goto timer)
:skiploop
goto loop
I have no idea where to start as when I search for this topic I get other languages or other methods that dont seem to either do it in real time or doesnt work at all. Thank you for any help given.
EDIT: The python script makes the writelines but I believe these can also be taken from the CMD process itself, not sure though.
EDIT:
public void StartBotBtn_Click(object sender, EventArgs e)
{
Process proc = new Process();
ProcessStartInfo si = new System.Diagnostics.ProcessStartInfo();
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.OutputDataReceived += ProcessOutputHandler;
proc.StartInfo.FileName = "C:\\Users\\gunzb\\Desktop\\Tarkov Bot\\start.bat";
proc.Start();
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
processid = proc.Id;
}
private void StopBotBtn_Click(object sender, EventArgs e)
{
Array.ForEach(Process.GetProcessesByName("py"), x => x.Kill());
Array.ForEach(Process.GetProcessesByName("cmd"), x => x.Kill());
}
private void ProcessOutputHandler(object sender, DataReceivedEventArgs e)
{
this.listBox1.Items.Add(e.Data); //This is where I get confused.
}

The requested operation requires elevation even after running visual studio as Administrator

I am trying to run and resize OSK from my winform application but I am getting this error:
The requested operation requires elevation.
I am running visual studio as administrator.
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = "c:\\windows\\system32\\osk.exe";
process.StartInfo.Arguments = "";
process.StartInfo.WorkingDirectory = "c:\\";
process.Start(); // **ERROR HERE**
process.WaitForInputIdle();
SetWindowPos(process.MainWindowHandle,
this.Handle, // Parent Window
this.Left, // Keypad Position X
this.Top + 20, // Keypad Position Y
panelButtons.Width, // Keypad Width
panelButtons.Height, // Keypad Height
SWP_SHOWWINDOW | SWP_NOZORDER); // Show Window and Place on Top
SetForegroundWindow(process.MainWindowHandle);
However,
System.Diagnostics.Process.Start("osk.exe");
Works just fine but it wont let me resize the keyboard
process.StartInfo.UseShellExecute = false will prohibit you from doing what you want to do. osk.exe is a bit special as only one instance can run at a time. So you must let the os handle the startup (UseShellExecute must be true).
(...) Works just fine but it wont let me resize the keyboard
Just make sure that process.MainWindowHandle is not IntPtr.Zero. Could take a while though, your'e not allowed to ask the process instance with process.WaitForInputIdle(), probably because the proc is run by the os. You could poll the handle though and then run your code. like this:
System.Diagnostics.Process process = new System.Diagnostics.Process();
// process.StartInfo.UseShellExecute = false;
// process.StartInfo.RedirectStandardOutput = true;
// process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = "c:\\windows\\system32\\osk.exe";
process.StartInfo.Arguments = "";
process.StartInfo.WorkingDirectory = "c:\\";
process.Start(); // **ERROR WAS HERE**
//process.WaitForInputIdle();
//Wait for handle to become available
while(process.MainWindowHandle == IntPtr.Zero)
Task.Delay(10).Wait();
SetWindowPos(process.MainWindowHandle,
this.Handle, // Parent Window
this.Left, // Keypad Position X
this.Top + 20, // Keypad Position Y
panelButtons.Width, // Keypad Width
panelButtons.Height, // Keypad Height
SWP_SHOWWINDOW | SWP_NOZORDER); // Show Window and Place on Top
SetForegroundWindow(process.MainWindowHandle);
Due note: use of Wait() (or Thread.Sleep); should be very limited in WinForms, it renders the ui thread unresponsive. You should probably use Task.Run(async () => ... here instead, to be able to use await Task.Delay(10), but that's a different story and complicates the code slightly.

PrintDialog shows behind all open windows

I have a simple PrintDialog (code below). My application is a tray application, meaning it has no windows in it and only contains a few simple right click options from the tray icon. Given a file path, the application will open a print dialog and let the user print the item.
I am seeing the following issue...the first time the print works, the dialog pops up to the top, taking precedence over all of my other open programs. After the first, the print dialog is always opened behind everything else that I have opened. For example, I have a web browser open on my screen, the print dialog will open behind that every time after the first print.
PrintDialog pd = new PrintDialog();
if (pd.ShowDialog() == DialogResult.OK)
{
ProcessStartInfo info = new ProcessStartInfo(filename);
info.Arguments = "\"" + pd.PrinterSettings.PrinterName + "\"";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.UseShellExecute = true;
info.Verb = "PrintTo";
try { Process.Start(info); }
catch (Exception e) {
// An exception occured while attempting to print
return false;
}
return true;
}
I was able to find an answer in this post:
Cannot show print dialog on the top of asp.net web control
Leaving the answer here as it took me multiple days to find something that actually worked. Hopefully this can be helpful to someone else.
//initialize a new window form
Form currentForm = new Form();
//show the form
currentForm.Show();
//Activate the form
currentForm.Activate();
//Set its TopMost to true, so it will bring the form to the top
currentForm.TopMost = true;
//Set it to be Focus
currentForm.Focus()
//set the form.visible = false
currentForm.Visible = false;
//start to show the print dialog
printDialog.ShowDialog(currentForm)
//close the new form
currentForm.Close();

C# Query: Command Window does not persist

I have the following code for a button click event. This event should open the command window and execute the application:
private void start_Click(object sender, EventArgs e)
{
if (textBox1.Text == " " || textBox2.Text == " ")
{
MessageBox.Show("Header File or Executable Missing");
}
else
{
Process.Start(textBox1.Text);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = textBox1.Text;
string filename = textBox1.Text;
int found = filename.LastIndexOf("\\");
int end = filename.Length;
string temp = filename.Substring(found);
startInfo.Arguments = temp + textBox2.Text;
Process.Start(startInfo);
}
}
The problem that I'm facing out here is that when I click the button, the command window does not persist and I don't know whether the command window displays an error message or not because it opens & closes in a flash. Can anybody tell me what is going wrong here and give me a few hints how to go about solving the issue?
If you want to start a new console application from your Windows Forms application you need to either pass in the path to such an application or to cmd.exe + the run command for that application. Make sure the code in your console application halts by asking for a Console.ReadKey(true) or similar.

Categories

Resources