如何在C#中启动另一个应用程序?

问题描述 投票:19回答:8

我有两个桌面应用程序。关闭第一个应用程序后,第一个应用程序将启动第二个应用程序。

完成第一次申请后如何开始第二次申请?

我的第一个应用创建一个单独的桌面

c# desktop-application launch
8个回答
17
投票

您可以使用.NET的Process Class来启动其他人描述的流程。然后问题是什么时候打电话。

在大多数情况下,使用Form.ClosingForm.Closed事件似乎是一个简单的选择。

但是,如果其他人可以处理该事件并且可以将CancelEventArgs.Cancel设置为true,则可能不是这样做的正确位置。此外,当Form.Closing被召唤时,Form.ClosedApplication.Exit()事件将不会被提升。如果发生任何未处理的异常,我不确定是否会引发任何一个事件。 (此外,您必须决定是否要在Application.Exit()或任何未处理的异常情况下启动第二个应用程序)。

如果你真的想确保在第一个应用程序(App1)退出后启动第二个应用程序(App2),你可以玩一个技巧:

  1. 创建一个单独的应用程序(App0)
  2. App0启动App1
  3. App0等待App1退出Process.WaitExit()
  4. App0启动App2并退出

下面附带的示例控制台应用程序显示了一个非常简单的案例:我的示例应用程序首先启动记事本。然后,当记事本退出时,它会启动mspaint并退出。

如果要隐藏控制台,只需在“项目属性”的“应用程序”选项卡下将“输出类型”属性从“控制台应用程序”设置为“Windows应用程序”即可。

示例代码:

using System;
using System.Diagnostics;

namespace ProcessExitSample
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {

                Process firstProc = new Process();
                firstProc.StartInfo.FileName = "notepad.exe";
                firstProc.EnableRaisingEvents = true;

                firstProc.Start();

                firstProc.WaitForExit();

                //You may want to perform different actions depending on the exit code.
                Console.WriteLine("First process exited: " + firstProc.ExitCode);

                Process secondProc = new Process();
                secondProc.StartInfo.FileName = "mspaint.exe";
                secondProc.Start();                

            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred!!!: " + ex.Message);
                return;
            }
        }
    }
}

18
投票

退出第一个申请时使用Process class

var p = new Process();
p.StartInfo.FileName   = "notepad.exe";  // just for example, you can use yours.
p.Start();

3
投票

您可以关闭它,所以当您即将退出第一个应用程序时,只需启动第二个应用程序:

System.Diagnostics.Process.Start(@"PATH\NAME.EXE");

1
投票

使用.NET的Process类。


0
投票

一些示例代码:

try
{
  stateMainLayout b = new stateMainLayout();
 b.Location = Screen.AllScreens[1].WorkingArea.Location;
 b.ShowDialog();
 }
catch
{
 stateMainLayout b = new stateMainLayout();
b.ShowDialog();
}

0
投票

CSharp / PowerShell调用另一个程序并发送/接收数据:qazxsw poi


0
投票

在某些情况下,有必要将Working目录添加到您的代码中,以使应用程序完美运行。特别是当应用程序依赖于DLL和其他资源时。

https://huseyincakir.wordpress.com/2014/12/23/sending-input-from-csharppowershell-to-another-program/

0
投票

这里ProcName表示您要启动的应用程序的名称,但它只能启动系统应用程序和其他一些应用程序

 TestProcess.StartInfo.FileName = "notepad.exe"; 
 TestProcess.StartInfo.WorkingDirectory = @"C:\\blah\blah\Directory of notepad.exe\";
 TestProcess.Start();
© www.soinside.com 2019 - 2024. All rights reserved.