C#中调用外部exe的使用、调用powershell、退出进程、委托和事件

针对几种情况,简单总结学习一下

竟然找到一个超级简单的方法调用exe文件

代码就一句,并且调用的效果特别好。加上后面的.WaitForExit()就是为了等调用的程序运行完后再执行下面的代码,没有后面的.WaitForExit() 无需等待程序完成后执行代码。

System.Diagnostics.Process.Start(Application.StartupPath + “你的应用程序.exe”);

System.Diagnostics.Process.Start(".\\CameraTool\\CameraPreview.exe").WaitForExit();

目前有一个工具需要cmd窗口打开工具界面,工具中无法关闭自身,必须关掉cmd窗口才可以。在C#中调用工具,cmd窗口未出现。

使用bat,批处理命令,可以同时打开cmd窗口和工具界面,C#再调用此bat.

调用的exe实时显示在窗口的,可以采用bat的方式来实现。


System.Diagnostics.Process类:用来启动和停止进程的。

1、

Process pr = new Process();//声明一个进程类对象
            process.StartInfo.FileName = "C:\\Keil_v5\\UV4\\UV4.exe";
            process.Start();

还可以简单点:Process的静态方法Start();

    Process.Start(String  fileName);(+4重载) //filiName 是你要运行的程序名,是物理路径

    Process.Start(String  fileName,string arguments)//filiName 是你要运行的程序名,是物理路径;arguments启动改程序时传递的命令行参数


各个参数的定义

Process类的StartInfo属性包含了一些进程启动信息,其中比较重要的几个

FileName                可执行程序文件名

Arguments              程序参数,已字符串形式输入 
CreateNoWindow     是否不需要创建窗口 
UseShellExecute      是否需要系统shell调用程序


            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序




2、调用powershell

            Process p = new Process();
            p.StartInfo.FileName = "PowerShell.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.Verb = "runas";
            p.StartInfo.CreateNoWindow = false;
            p.Start();
            p.StandardInput.WriteLine("set-ExecutionPolicy RemoteSigned");
            p.StandardInput.WriteLine("y");
            p.StandardInput.WriteLine("cd SVC_Tool_1.0.0.0_Master_Test");
            p.StandardInput.WriteLine(".\\Add-AppDevPackage.ps1");
            p.StandardInput.AutoFlush = true;
            p.WaitForExit();
            p.Close();

3、退出进程

若想关闭主程序的同时也关闭调用的程序,需要在退出程序的按钮事件中添加如下代码:

           Process[] pProcess;
            pProcess = Process.GetProcesses();
            for (int i = 1; i <= pProcess.Length - 1; i++)
            {
                if (pProcess[i].ProcessName == "应用程序名字")   //任务管理器应用程序的名
                {
                    pProcess[i].Kill();
                    break;
                }
            }

4、事件和委托

using System;
using System.Collections.Generic;
using System.Text;

namespace Delegate {
    // 热水器
    public class Heater {
       private int temperature;
       public delegate void BoilHandler(int param);   //声明委托
       public event BoilHandler BoilEvent;        //声明事件

       // 烧水
       public void BoilWater() {
           for (int i = 0; i <= 100; i++) {
              temperature = i;

              if (temperature > 95) {
                  if (BoilEvent != null) { //如果有对象注册
                      BoilEvent(temperature);  //调用所有注册对象的方法
                  }
              }
           }
       }
    }

    // 警报器
    public class Alarm {
       public void MakeAlert(int param) {
           Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:", param);
       }
    }

    // 显示器
    public class Display {
       public static void ShowMsg(int param) { //静态方法
           Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", param);
       }
    }
    
    class Program {
       static void Main() {
           Heater heater = new Heater();
           Alarm alarm = new Alarm();

           heater.BoilEvent += alarm.MakeAlert;    //注册方法
           heater.BoilEvent += (new Alarm()).MakeAlert;   //给匿名对象注册方法
           heater.BoilEvent += Display.ShowMsg;       //注册静态方法

           heater.BoilWater();   //烧水,会自动调用注册过对象的方法
       }
    }
}

输出为:
Alarm:嘀嘀嘀,水已经 96 度了:
Alarm:嘀嘀嘀,水已经 96 度了:
Display:水快烧开了,当前温度:96度。

总结:简单总结一下就是,声明一个委托和事件,委托和调用的方法返回值和参数相同。在需要调用事件的方法中,调用事件。在程序运行中,别忘记注册事件。

再举个使用过的例子:

声明委托和事件

        /// <summary>
        /// 事件,数据到达,处理此事件以接受输入数据
        /// </summary>
        public event EventHandler<byte[]> GetFeatureDataReceived;
        protected virtual void OnGetFeatureDataReceived(byte[] e)
        {
            if (GetFeatureDataReceived!=null)
            {
                GetFeatureDataReceived(this,e);
            }
        }

注册事件(主程序运行入口代码

       public FormMain()
        {
            InitializeComponent();

            //getfeature 得到的数据进行处理
            myHid.GetFeatureDataReceived += new EventHandler<byte[] >(myHID_received_packet_management);
        }

调用事件

       public HID_RETURN Get_Feature(report r)
        {
            if (deviceOpened)
            {
                try
                {
                    byte[] buffer = new byte[featureReportLength];
                    buffer[0] = r.reportID;
                    int maxBufferLength = 0;

                    if (r.reportBuff.Length < featureReportLength - 1)
                    {
                        maxBufferLength = r.reportBuff.Length;
                    }

                    else
                    {
                        maxBufferLength = featureReportLength - 1;
                    }

                    for (int i = 1; i <= maxBufferLength; i++)
                    {
                        buffer[i] = r.reportBuff[i - 1];
                    }

                    if (HidD_GetFeature(device, buffer, featureReportLength))
                    {
                        OnGetFeatureDataReceived(buffer);

                        return HID_RETURN.SUCCESS;
                    }

                    else
                    {
                        return HID_RETURN.SET_FEATURE_FAILED;
                    }
                }
                catch
                {
                    EventArgs ex = new EventArgs();
                   
                    OnDeviceRemoved(ex);
                    return HID_RETURN.SET_FEATURE_FAILED;
                }
            }
            return HID_RETURN.SET_FEATURE_FAILED;
        }


定义使用委托的方法(按照正常定义方法的方式

        //Dealing with the received data packet
        private void myHID_received_packet_management(object sender, byte[] e)
        {
            received_packet = e;
        }

...


猜你喜欢

转载自blog.csdn.net/yanhuatangtang/article/details/80014448