简体   繁体   中英

How to start notepad.exe in hidden mode in windows application?

I am trying to start notepad.exe in hidden mode like below is the code which i have written:-

try
{
     ProcessStartInfo startInfo = new ProcessStartInfo();
     startInfo.CreateNoWindow = false;
     startInfo.UseShellExecute = false;
     startInfo.FileName = "notepad.exe";
     startInfo.WindowStyle = ProcessWindowStyle.Hidden;
     startInfo.Arguments = @"C:\Users\Sujeet\Documents\test.txt";
}
catch
{ 

}

but the problem is process(ie notepad.exe) gets successfully started but startInfo.WindowStyle = ProcessWindowStyle.Hidden is not working. I have surfed net for this problem but was not able to get the proper solution.

This version works on my box:

try
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = false;
    startInfo.UseShellExecute = true;
    startInfo.FileName = @"%windir%\system32\notepad.exe";
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.Arguments = @"C:\Users\Sujeet\Documents\test.txt";
    Process.Start(startInfo);
}
catch
{ }

I only get a Win32Exception telling that the file (test.txt) cannot be found, but the process runs, and no window is visible.

Take care to exit the process, or the user will end up with invisible processes running.

If your application is uncooperative (like calc.exe you mentioned in the comments), you could try the following:

Define somewhere:

    [DllImport("user32.dll")]
    private static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
    const int SW_SHOW = 5;
    const int SW_HIDE = 0;

And then do the following after crating the process:

    var proc = Process.Start(startInfo);
    while (proc.MainWindowHandle == IntPtr.Zero) //note: only works as long as your process actually creates a main window.
        System.Threading.Thread.Sleep(10);
    ShowWindow(proc.MainWindowHandle, SW_HIDE);

I don't know why the path %windir%\\system32\\calc.exe does not work, but it works with startInfo.FileName = @"c:\\windows\\system32\\calc.exe";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM