Unity调用CMD窗口启动其他程序

Unity调用CMD窗口启动其他程序

引用命名空间

using System.Diagnostics.Process;

代码段

private Thread _ClientThread;
private Progress _ClientProgress;

	///启动的外部接口,调用该方法启动
  	public void StartClient()
    {
        _ClientThread = new Thread(RunClient);
        _ClientThread.Start();
    }
    
 	void RunClient()
    {
        string result = Client();
        UnityEngine.Debug.Log("ClientResult:      "+result);
    }

	string Client()
    {
        _ClientProcess = new System.Diagnostics.Process();
        _ClientProcess.StartInfo.FileName = "cmd.exe";

        _ClientProcess.StartInfo.UseShellExecute = false;
        _ClientProcess.StartInfo.RedirectStandardInput = true;
        _ClientProcess.StartInfo.RedirectStandardOutput = true;
        _ClientProcess.StartInfo.RedirectStandardError = true;
        _ClientProcess.StartInfo.CreateNoWindow = true;
        _ClientProcess.Start();
        //这里我将exe程序放在了streamingassets目录下
        //你也可以指定固定地址
        //ex:_ClientProcess.StandardInput.WriteLine(@"E:\Project\TeamSpeakUnity\ts3_sdk_3.0.4.4\bin\windows\win32\ts3_client_sample.exe" + "&exit");
		_ClientProcess.StandardInput.WriteLine(Application.streamingAssetsPath
		+@"\ts3_sdk_3.0.4.4\bin\windows\win32\ts3_client_sample.exe" + "&exit");
		 
        _ClientProcess.StandardInput.AutoFlush = true;
        _ClientProcess.StartInfo.StandardErrorEncoding = System.Text.Encoding.UTF8;
        _ClientProcess.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
        
        return _ClientProcess.StandardOutput.ReadToEnd();

    }

	///结束程序的时候关闭进程
	private void OnDestroy()
    {
        
        if (_ClientProcess!=null&&!_ClientProcess.HasExited)
        {
            _ClientProcess.StandardInput.WriteLine("q");
            _ClientProcess.Kill();
            UnityEngine.Debug.Log("Exit");
        }
    }
发布了1 篇原创文章 · 获赞 0 · 访问量 4

猜你喜欢

转载自blog.csdn.net/liyujieaaa/article/details/105678377
今日推荐