C#启动应用程序并传递多个参数

12

我一直尝试从C#应用程序启动一个应用程序,但是它无法正常启动。通过cmd启动应用程序以及参数会显示一个小窗口显示输出,然后将应用程序最小化到系统托盘。

使用下面的代码从C#应用程序启动应用程序会导致在任务管理器中出现该进程,但没有其他任何内容,没有输出窗口,也没有系统托盘图标。可能的问题是什么?

    myProcess.StartInfo.FileName = ...;
    myProcess.StartInfo.Arguments = ...;
    myProcess.Start();

我尝试传递以下内容

    myProcess.StartInfo.RedirectStandardOutput = true; //tried both
    myProcess.StartInfo.UseShellExecute = false; //tried both 
    myProcess.StartInfo.CreateNoWindow = false;

使用

    Process.Start(Filename, args)

也没有起作用。非常感谢任何有关如何解决此问题的帮助。

更新: 我认为问题可能是要传递给进程的多个参数。

RunMode=Server;CompanyDataBase=dbname;UserName=user;PassWord=passwd;DbUserName=dbu;Server=localhost;LanguageCode=9

敬礼


尝试用单引号括起参数。 - leppie
4个回答

14
我在你的代码中没有看到任何错误。我写了一个小程序,将其参数打印到控制台上。
static void Main (string[] args)
{
     foreach (string s in args)
         Console.WriteLine(s);
     Console.Read(); // Just to see the output
}

然后我把它放在C盘,名字叫做"PrintingArgs.exe"的应用程序,所以我又写了一个执行第一个应用程序的程序。
Process p = new Process();
p.StartInfo.FileName = "C:\\PrintingArgs.exe";
p.StartInfo.Arguments = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18";
p.Start();

这样可以得到我想要的数字列表输出。调用PrintingArgs的应用程序在达到p.Start()时退出,可以通过使用p.WaitForExit()或者只是Console.Read()来避免这种情况。 此外,我还使用了UseShellExecute和CreateNoWindow两个选项。只有在这种情况下。
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;

使PrintingArgs应用程序不显示窗口(即使我只设置p.StartInfo.CreateNoWindow = true,它仍然显示一个窗口)。

现在我想到的是,也许您以错误的方式传递了参数,导致其他程序失败并立即关闭,或者您没有指向正确的文件。检查路径和名称,以找出可能遗漏的任何错误。 此外,使用

 Process.Start(fileName, args);

不使用您在StartInfo中设置的信息到您的Process实例。

希望这能帮到您, 谢谢。


另一个提醒,对于使用 Process 的人,请不要忘记它们需要被处理。因此,最好将它们放在 using 子句中。 例如: using (Process p = new Process()) { //做一些事情 } - mickeymicks

6

不确定是否还有人在关注这个问题,但这是我想到的。

string genArgs = arg1 + " " + arg2;
string pathToFile = "Your\Path";
Process runProg = new Process();
try
{
    runProg.StartInfo.FileName = pathToFile;
    runProg.StartInfo.Arguments = genArgs;
    runProg.StartInfo.CreateNoWindow = true;
    runProg.Start();
}
catch (Exception ex)
{
    MessageBox.Show("Could not start program " + ex);
}

在字符串中添加一个空格允许传入两个参数到我想要运行的程序中。执行代码后,程序顺利运行。


2

您是否将ProcessWindowStyle设置为隐藏?以下是我的代码,它可以很好地工作:

Process p=new Process();
p.StartInfo.FileName = filePath;//filePath of the application
p.StartInfo.Arguments = launchArguments;
p.StartInfo.WindowStyle = (ProcessWindowStyle)ProcessStyle;//Set it to **Normal**
p.Start();

1
      System.Diagnostics.Process.Start(FileName,args);

例如

     System.Diagnostics.Process.Start("iexplore.exe",Application.StartupPath+ "\\Test.xml");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接