WPF 两个程序之间传递参数(Process)

程序一 :WpfApplication1 传递参数

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //ProcessStartInfo ps = new ProcessStartInfo(@"‪F:\Code\WpfApplication2\bin\Debug\WpfApplication2.exe", textBox.Text.ToString());
            //Process.Start(ps);

            //Process.Start(@"‪F:\Code\WpfApplication2\bin\Debug\WpfApplication2.exe", textBox.Text.ToString());
            try
            {
                //引用:using System.Diagnostics;
                Process pro = new Process();
                pro.StartInfo.FileName = @"F:\ZJDCode\WpfApplication2\bin\Debug\WpfApplication2";
                pro.StartInfo.Arguments = textBox.Text.ToString();
                pro.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:" + ex.Message);
            }
        }
    }
}

程序二:WpfApplication2 接收参数

namespace WpfApplication2
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public MainWindow(string[] args)
        {
            InitializeComponent();
            if (args.Length > 0)
            {
                label1.Content = "获取到的参数:" + args[0];
            }
        }
    }
}

需要在WpfApplication2里手动创建Program类

namespace WpfApplication2
{
    class Program
    {
        //在这个例子中,[STAThread]属性确保了在打开文件对话框时,主线程采用正确的线程模型(STA),这样就可以避免与文件对话框的潜在线程安全问题和其他与COM交互相关的问题。
        //没有[STAThread]属性的情况下,如果尝试在MTA模型中打开文件对话框,我们可能会遇到异常或者不可预测的行为。因此,每当我们的应用程序需要与要求STA模型的COM组件交云时(常见于UI相关的操作和老式的COM组件调用),我们都应该在Main方法上应用[STAThread]属性。
        //[STAThread]属性:这个属性应用于Main方法上,表明应用程序的主线程必须在STA模型下运行。这意味着该线程将创建一个消息队列,用于处理来自其他线程的请求,这是处理Windows窗体事件和某些COM组件(如剪贴板操作、OLE拖放操作等)的必要条件。
        //STAThread属性用于指示应用程序的主线程使用单线程单元(Single Thread Apartment)模型。这是线程模型的一种,与COM(Component Object Model)交云通信有关。
        [STAThread]// 标注主线程为STA模型
        //单线程单元(STA)模型:在STA模型中,一个线程不能同时被多个线程访问。若要在其他线程中访问STA线程中的COM对象,必须进行线程间的消息传递。STA模型简化了编写线程安全代码的过程,因为它通过消息队列序列化对COM对象的访问。
        static void Main(string[] args)
        {
            MessageBox.Show("进入Main函数体了(参数:" + args.Length + ")");

            //方法一 打开指定窗口
            //MainWindow window = new MainWindow();
            //var app = new App();
            //app.Run(window);
            //方法二 程序设置的那个窗口就打开那个窗口
            //var app = new App();
            //app.InitializeComponent();
            //方法三
            CustomApplication app = new CustomApplication();
            app.Run();
        }
    }
    class CustomApplication : Application
    {
        //StartupEventArgs     引用:System.Windows
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            MainWindow window = new MainWindow(e.Args);
            window.Show();
        }
    }
}

WpfApplication2项目属性设置启动对象WpfApplication2.Program,新建完Program类并添加Main函数之后在启动对象里才会显示WpfApplication2.Program选项。

以上是实现程序之间传参的全过程。

下面做一些扩展:检查程序是否启动。如果已经启动就打开现有程序,没启动就正常打开

只需要修改一下WpfApplication2.Program类即可。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApplication2
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {//获取启动进程名
            string strProcessName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
            //检查进程是否已经启动,已经启动则退出程序,显示已启动的程序。 
            if (System.Diagnostics.Process.GetProcessesByName(strProcessName).Length > 1)
            {
                RaiseOtherProcess();
                Application.Current.Shutdown();
                return;
            }
            else
            {
                //MessageBox.Show("进入Main函数体了(参数:" + args.Length + ")");
                CustomApplication app = new CustomApplication();
                app.Run();
            }
        }

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);
        private const int SW_RESTORE = 9;
        /// <summary>
        /// 激活已打开窗口
        /// </summary>
        public static void RaiseOtherProcess()
        {
            Process proc = Process.GetCurrentProcess();
            foreach (Process otherProc in
                Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName))
            {
                if (proc.Id != otherProc.Id)
                {
                    IntPtr hWnd = otherProc.MainWindowHandle;
                    if (IsIconic(hWnd))
                    {
                        ShowWindowAsync(hWnd, 9);
                    }
                    SetForegroundWindow(hWnd);
                    break;
                }
            }
        }

    }
    class CustomApplication : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            MainWindow window = new MainWindow(e.Args);
            window.Show();
        }
    }
}

  • 25
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
WPF MVVM 架构中,可以使用 InvokeCommandAction 来触发 ViewModel 中的命令,并且可以传递一个参数。如果需要传递多个参数,可以使用以下方法: 1. 使用命令参数对象 定义一个类,包含需要传递的多个参数,例如: ``` public class CommandParameter { public string Parameter1 { get; set; } public int Parameter2 { get; set; } } ``` 在 XAML 中,使用该类作为 InvokeCommandAction 的 CommandParameter 属性的值: ``` <i:InvokeCommandAction Command="{Binding MyCommand}" CommandParameter="{Binding CommandParameter}" /> ``` 在 ViewModel 中,命令的 Execute 方法可以接收该类的实例作为参数: ``` public RelayCommand<CommandParameter> MyCommand { get; set; } public void MyCommandExecute(CommandParameter parameter) { // 使用参数 } ``` 2. 使用触发事件的参数 在 XAML 中,可以使用 EventTrigger 触发一个事件,并且可以使用 EventTrigger 的 EventArgsConverter 属性将事件参数转换为需要的类型。例如: ``` <i:Interaction.Triggers> <i:EventTrigger EventName="MyEvent"> <i:InvokeCommandAction Command="{Binding MyCommand}"> <i:InvokeCommandAction.CommandParameter> <MultiBinding Converter="{StaticResource MyConverter}"> <Binding Path="Parameter1" /> <Binding Path="Parameter2" /> </MultiBinding> </i:InvokeCommandAction.CommandParameter> </i:InvokeCommandAction> </i:EventTrigger> </i:Interaction.Triggers> ``` 在这里,使用 MultiBinding 将多个绑定值传递给一个转换器。转换器将这些值转换为需要的类型,并且将它们封装到一个对象中,然后作为命令的参数传递给 ViewModel。 在 ViewModel 中,命令的 Execute 方法可以接收该对象作为参数: ``` public RelayCommand<MyParameter> MyCommand { get; set; } public void MyCommandExecute(MyParameter parameter) { // 使用参数 } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值