ict.shenzhi/Assets/Scripts/ProcessControl.cs

96 lines
2.3 KiB
C#

using UnityEngine;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System;
public class ProcessControl : MonoBehaviour
{
private Process process;
public static ProcessControl Instance;
void Awake()
{
Instance = this;
WindowManager.Instance.SwitchResolution(WindowManager.ScreenResolution.MAX_SCREEN);
}
// 启动外部程序
public void StartProcess(string StartupParameters)
{
#if UNITY_EDITOR
#else
if (process != null && !process.HasExited)
{
UnityEngine.Debug.Log("Process is already running.");
return;
}
try
{
process = new Process();
process.StartInfo.FileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\ToolsForm", "ToolsForm.exe"); // 设置.exe路径
process.StartInfo.Arguments = StartupParameters; // 可以设置参数,如果需要的话
process.Start(); // 启动.exe文件
UnityEngine.Debug.Log("Process started.");
}
catch (System.Exception ex)
{
UnityEngine.Debug.LogError("Error starting process: " + ex.Message);
}
#endif
}
// 结束外部程序
public void KillProcess()
{
#if UNITY_EDITOR
#else
if (process != null && !process.HasExited)
{
try
{
process.Kill(); // 结束进程
UnityEngine.Debug.Log("Process terminated.");
}
catch (System.Exception ex)
{
UnityEngine.Debug.LogError("Error terminating process: " + ex.Message);
}
}
else
{
UnityEngine.Debug.Log("No process is running.");
}
#endif
}
private void OnApplicationQuit()
{
KillProcess();
}
private void OnDisable()
{
KillProcess();
}
/*
// 示例使用
void Update()
{
// 使用示例:按下 P 键启动程序
if (Input.GetKeyDown(KeyCode.P))
{
StartProcess(); // 替换为实际的exe路径
}
// 使用示例:按下 K 键结束程序
if (Input.GetKeyDown(KeyCode.K))
{
KillProcess();
}
}
*/
}