c#实现进程开启另一个进程时传递参数
前言
例如:主程序下可能会挂在其他程序,但是他们可能公用一个登陆账号或站点,这时就需要主程序开启其下的子程序时将站点消息,登录消息或者权限等相关信息传递到子进程中以作判断使用,本文就简单介绍了两个进程之间传递参数的基础内容。
一、实现过程
示例:这里主要创建了一个基于.NET Framework的控制台程序和一个winform程序,实现逻辑便是控制台程序启动时会去调用编译好的winform的.exe文件,并且传递参数。
二、实现步骤
1.创建控制台应用程序
Main方法代码如下(示例):
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppone
{
internal class Program
{
static void Main(string[] args)
{
ProcessStartInfo process = new ProcessStartInfo();
process.FileName = @"D:\c#study\WindowsFormsApptwo\bin\Debug\WindowsFormsApptwo.exe";
string arg1 = "进程参数1";
string arg2 = "进程参数2";
process.Arguments = string.Format("{0} {1}", arg1, arg2); //多个参数用空格隔开
process.WindowStyle = ProcessWindowStyle.Normal;
Process.Start(process);
Console.Read();
}
}
}
其中process.FileName是你要启动的winfrom程序编译出来的exe文件的路径
2.创建winfrom程序
Winfrom主程序代码如下修正(示例):
1. Program下的Main方法代码
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
public static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args));
}
修正点 Main方法添加 string[] args的参数以便接收控制台传过来的参数,
new Form1() => new Form1(args)以便展示参数使用
2.From1页面中拽入两个lable
From1.cs代码如下(示例)
public Form1(string[] args)
{
InitializeComponent();
label1.Text = args[0];
label2.Text = args[1];
}
修正点如下 Form1()=>Form1(string[] args)添加传过来的参数,其次还有就是InitializeComponent()方法初始化窗体组件之后 对添加的label组件的text进行修正。
3.运行结果如下
1.启动控制台程序
2.调用的winform程序
在Form1页面中成功展示参数
总结
以上就是今天要讲的内容,本文仅仅简单介绍了一个进程调用另一个进程时传递参数简单应用。