如何在Windows应用程序中以隐藏模式启动Notepad.exe



我试图以隐藏模式启动notepad.exe,如下所示是我编写的代码: -

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

但是问题是过程(即Notepad.exe)成功启动,但StartInfo.WindowStyle = ProcessWindowStyle.hidden不起作用。我已经为这个问题浏览了网,但无法获得适当的解决方案。

此版本在我的框上工作:

try
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = false;
    startInfo.UseShellExecute = true;
    startInfo.FileName = @"%windir%system32notepad.exe";
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.Arguments = @"C:UsersSujeetDocumentstest.txt";
    Process.Start(startInfo);
}
catch
{ }

我只得到一个win32 exception,告诉该文件(test.txt)找不到,但是该过程运行,并且看不到窗口。

小心地退出流程,否则用户最终会运行不可见的过程。

如果您的应用程序不合作(例如您在评论中提到的calc.exe),则可以尝试以下内容:

在某个地方定义:

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

,然后在将过程中进行以下操作:

    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);

我不知道为什么路径%windir%system32calc.exe不起作用,但它可以与startInfo.FileName = @"c:windowssystem32calc.exe";

一起使用

最新更新