讲的比较详细只是实现方式不同:WPF 两个程序之间传递参数(Process)_wpf的exe程序传入参数-优快云博客
主窗口
/// <summary>
/// ShellExecute
/// </summary>
/// <param name="hwnd">指定父窗口句柄:ntPtr.Zero</param>
/// <param name="lpszOp">指定要进行的操作:Open</param>
/// <param name="lpszFile">指定要打开的文件名|路径</param>
/// <param name="lpszParams">指定命令行参数: 0 | ""</param>
/// <param name="lpszDir">用于指定默认目录:0 | ""</param>
/// <param name="FsShowCmd">显示模式: 0:隐藏 1~11</param>
/// <returns></returns>
[DllImport("shell32.dll")]
public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
public void sc(string exepath, string sof_Name)
{
ShellExecute(IntPtr.Zero, new StringBuilder("Open"), new StringBuilder(exepath + "\\rest.exe"), new StringBuilder("shortcut " + exepath + " " + sof_Name), new StringBuilder(exepath), 1);
//ShortCut.CreateShortCut(exepath, sof_Name);
}
//例:嵌套在按钮的单击事件里面
public void StartProgram()
{
string url = @"F:\MainWindow.exe";//这里是要打开的程序路径,不是当前的程序路径
Student stu = new Student();
stu.ID = 1;
stu.Name = "张三";
stu.Age = 18;
//把Student对象序列化为Json字符串
//引用:System.Web.Script.Serialization;
string paras = new JavaScriptSerializer().Serialize(stu);
//获取启动应用程序的可执行文件的路径,包括可执行文件的名称。 就是可以获取到当前程序的.exe文件
string exe_path = System.Windows.Forms.Application.ExecutablePath; //System.Diagnostics.Process.GetCurrentProcess
//启动MainWindow程序
ShellExecute(IntPtr.Zero, new StringBuilder("Open"), new StringBuilder(url), new StringBuilder(paras.Replace("\"", "\\\"") + " " + exe_path), new StringBuilder(url.Replace("MainWindow.exe", string.Empty)), 1);
//关闭当前程序
//this.Close();
}
class Student
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
创建Program.cs类
namespace MainWindow
{
class Program
{
//标注主线程为STA模型
[STAThread]
static void Main(string[] args)
{
MessageBox.Show("是否可以获取到参数:"+args.Length );
bool flag;
Application.EnableVisualStyles();//启用可视化样式
Application.SetCompatibleTextRenderingDefault(false);//将某些控件上定义的 UseCompatibleTextRendering 属性设置为应用程序范围内的默认值。
using (new System.Threading.Mutex(true, Application.ProductName, out flag))
{
if (flag)
{
// args没有参数表示正常运行
if (args.Length > 0)
{
LoginWindow win= new LoginWindow(args);
//MVVM
//win.DataContext = new LoginWindowViewModel();
var app = new App();
app.Run(win);
}
else
{
var app = new App();
app.InitializeComponent();
app.Run();
}
}
else
{
MessageBox.Show("应用程序已经在运行中...");
Environment.Exit(1);
}
}
}
}
}
MVVM窗口接收参考:
Auto_Reg window = new Auto_Reg (args);
window.DataContext = new Auto_RegViewModel(args); //把ViewModel 赋值给上下文
var app = new App();
app.Run(window);