Opening a process in C# with hidden window - c#

I have a function for starting processes on a local machine:
public int StartProcess(string processName, string commandLineArgs = null)
{
Process process = new Process();
process.StartInfo.FileName = processName;
process.StartInfo.Arguments = commandLineArgs;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.ErrorDialog = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
return process.Id;
}
It is supposed to start the process without opening a new window. Indeed, when I test it with timeout.exe no console window is opened. But when I test it with notepad.exe or calc.exe their windows still open.
I saw online that this method works for other people. I'm using .NET 4.0 on Windows 7 x64.
What am I doing wrong?

The CreateNoWindow flag applies to Console processes only.
See here for the details:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx
Secondly applications can ignore the WindowStyle argument - it has effect the first time the new application calls ShowWindow, but subsequent calls are under the control of the application.

Following program will show/hide the window:
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
const int SW_SHOW = 5;
static void Main()
{
// The 2nd argument should be the title of window you want to hide.
IntPtr hWnd = FindWindow(null, "Untitled - Notepad");
if (hWnd != IntPtr.Zero)
{
//ShowWindow(hWnd, SW_SHOW);
ShowWindow(hWnd, SW_HIDE); // Hide the window
}
}
}
Source: http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/1bc7dee4-bf1a-4c41-802e-b25941e50fd9

You need to remove the process.StartInfo.UseShellExecute = false
public int StartProcess(string processName, string commandLineArgs = null)
{
Process process = new Process();
process.StartInfo.FileName = processName;
process.StartInfo.Arguments = commandLineArgs;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.ErrorDialog = false;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
return process.Id;
}

Related

open external application in .Net Form panel

I want to open an external application in my form like this
Example
for that I wrote a class to open any applications and set a panel as the parent.
class ApplicationStarter
{
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
Process app;
public ApplicationStarter(string path, Panel panel)
{
try
{
ProcessStartInfo psi = new ProcessStartInfo(path);
psi.WindowStyle = ProcessWindowStyle.Minimized;
app = Process.Start(psi);
Thread.Sleep(500);
psi.UseShellExecute = false;
SetParent(app.MainWindowHandle, panel.Handle);
psi.WindowStyle = ProcessWindowStyle.Maximized;
psi.CreateNoWindow = true;
MessageBox.Show($"Application is started at {panel.Name}");
}
catch (Exception ex)
{
Log.Write($"Application {path} could not be started {ex.Message}", Log.LogState.FatalError, Log.System.ServerManager);
}
}
}
This class opens the application in the correct position and size, but the parent is not set and the application is not in the form.
Does anyone have any ideas how to implement this?

Bring process to focus c# (ASP.net)

I have created a web application that will call a window based application using:
#region Process
public static string shell_exec(string path, string args)
{
var p = new ProcessStartInfo();
// Redirect the output stream of the child process.
p.UseShellExecute = false;
p.LoadUserProfile = true;
p.RedirectStandardOutput = true;
p.FileName = path;
p.Arguments = args;
p.WindowStyle = ProcessWindowStyle.Normal;
var pc = Process.Start(p);
WindowHelper.BringProcessToFront(pc);
string output = pc.StandardOutput.ReadToEnd();
pc.WaitForExit();
return output;
}
#endregion
this is published using IIS Express server, the process.start() calls the application and shows in the top most (obviously because i set the property topmost true) but not in the taskbar (didn't activate the load event or not focused)
I also used bringprocesstofront function but didn't do anything:
const int SW_RESTORE = 9;
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr handle);
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool ShowWindow(IntPtr handle, int nCmdShow);
[System.Runtime.InteropServices.DllImport("User32.dll")]
private static extern bool IsIconic(IntPtr handle);
public static void BringProcessToFront(Process process)
{
IntPtr handle = process.MainWindowHandle;
if (IsIconic(handle))
{
ShowWindow(handle, SW_RESTORE);
}
SetForegroundWindow(handle);
}
am i missing something in my code?
The external process im calling is an application that will register a persons fingerprint (using DPFP digital persona, creating it in window based unless there is for web or javascript)

c# .NEt 3.5 Unable to Hide CMD Window When Running a Process as User - Form Application

I am trying to run a bunch of processes in the background using the CMD prompt from my support application.
I have successfully done this for standard commands, but when trying to run a command as an administrator (to retrieve and end processes), the console window will briefly appear on the screen.
Code:
public static bool checkRunning(string procName)
{
var ss = new SecureString();
ss.AppendChar('T');
ss.AppendChar('a');
ss.AppendChar('k');
ss.AppendChar('e');
ss.AppendChar('c');
ss.AppendChar('a');
ss.AppendChar('r');
ss.AppendChar('e');
ss.AppendChar('9');
ss.AppendChar('9');
ss.MakeReadOnly();
//ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/C tasklist /S " + Program.servName + " /FI \"SESSION eq " + Program.sessID + "\" /FO CSV /NH")
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C tasklist /S " + Program.servName + " /FI \"SESSION eq " + Program.sessID + "\" /FO CSV /NH";
startInfo.WorkingDirectory = #"C:\windows\system32";
startInfo.Verb = "runas";
startInfo.Domain = "mydomain";
startInfo.UserName = "ADMINuser";
startInfo.Password = ss;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
string strCheck = " ";
Process proc = Process.Start(startInfo);
proc.OutputDataReceived += (x, y) => strCheck += y.Data;
proc.BeginOutputReadLine();
proc.WaitForExit();
if (strCheck.Contains(procName))
{
return true;
}
else
{
return false;
}
}
From what I understand, setting shellExecute=false, createNoWindow=true and ProcessWindowStyle.Hidden should resolve the issue, but I believe it is not working due to the required admin log in.
Does anyone know of a solution or suitable workaround to this problem?
Any help is much appreciated,
Many thanks
You can use following code :
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int SW_HIDE = 0;
const int SW_SHOW = 5;
static void Main(string[] args)
{
var handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE);
}
From MSDN site on ProcessStartInfo.CreateNoWindow Property :
Remarks
If the UseShellExecute property is true or the UserName and Password
properties are not null, the CreateNoWindow property value is ignored
and a new window is created.
There is no workaround or resolution mentioned, and I have been unable to find one anywhere.
I have had to resort to me application briefly displaying CMD windows when running certain processes (The CreateNoWindow property works when not using UserName and Password).

How can I start a process in the background?

I can't seem to find an answer on Google or here on StackOverflow.
How can I start a process in background (behind the active window)? Like, when the process starts, it will not interrupt the current application the user is using.
The process won't pop out in front of the current application, it will just start.
This is what I'm using:
Process.Start(Chrome.exe);
Chrome pops up in front of my application when it's started. How can I make it start in background?
I've also tried:
psi = new ProcessStartInfo ("Chrome.exe");
psi.UseShellExecute = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.WindowStyle = ProcessWindowStyle.Minimized;
Process.Start(psi);
But there's no difference at all from the previous one.
Thanks.
Try this:
Process p = new Process();
p.StartInfo = new ProcessStartInfo("Chrome.exe");
p.StartInfo.WorkingDirectory = #"C:\Program Files\Chrome";
p.StartInfo.CreateNoWindow = true;
p.Start();
Also, if that doesn't work, try adding
p.StartInfo.UseShellExecute = false;
Below code should do what you need:
class Program
{
static void Main(string[] args)
{
var handle = Process.GetCurrentProcess().MainWindowHandle;
Process.Start("Chrome.exe").WaitForInputIdle();
SetForegroundWindow(handle.ToInt32());
Console.ReadLine();
}
[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);
}

How do I open maximized internet explorer?

I have to open maximized internet explorer using C#. I have tried the following:
try
{
var IE = new SHDocVw.InternetExplorer();
object URL = "http://localhost/client.html";
IE.ToolBar = 0;
IE.StatusBar = true;
IE.MenuBar = true;
IE.AddressBar = true;
IE.Width = System.Windows.Forms.SystemInformation.VirtualScreen.Width;
IE.Height = System.Windows.Forms.SystemInformation.VirtualScreen.Height;
IE.Visible = true;
IE.Navigate2(ref URL);
ieOpened = true;
break;
}
catch (Exception)
{
}
I can open with different sizes, but I couldn't find how to open maximized IE. I have checked the msdn, there is no property to for maximize.
Please give me some suggestions.
PS: I am developing C# console application, .Net4.5, and VS2012
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Maximize_IE
{
class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
static void Main(string[] args)
{
var IE = new SHDocVw.InternetExplorer();
object URL = "http://google.com/";
IE.ToolBar = 0;
IE.StatusBar = true;
IE.MenuBar = true;
IE.AddressBar = true;
IE.Visible = true;
ShowWindow((IntPtr)IE.HWND, 3);
IE.Navigate2(ref URL);
//ieOpened = true;
}
}
}
I would use the process method.
You could start any executable and
It has a property which starts your process maximized
ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
startInfo.WindowStyle = ProcessWindowStyle.Maximized;
startInfo.Arguments = "www.google.com";
Process.Start(startInfo);
Quick google of "csharp maximize SHDocVw window" gives this example:
[DllImport ("user32.dll")]
private static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
private const int SW_MAXIMISE = 3;
public void OpenWindow()
{
SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer(); //Instantiate the class.
ShowWindow((IntPtr)ie.HWND, SW_MAXIMISE); //Maximise the window.
ie.Visible = true; //Set the window to visible.
}
try this:
var proc = new Process
{
StartInfo = {
UseShellExecute = true,
FileName = "http://localhost/client.html",
WindowStyle = ProcessWindowStyle.Maximized
}
};
proc.Start();

Categories