Unity打开电脑本地计算器exe文件(调用PC平台下外部命令的方法)

C#为我们提供了System.Diagnostics.Process.Start()方法,在Windows平台下可以调用外部的命令

测试代码:

/// <summary>
    /// exe在电脑下的路径名,计算器比较特殊直接打开calc.exe即可
    /// 如需打开其他exe,则需完整路径名称
    /// </summary>
    private string path = "calc.exe";//fsquirt.exe蓝牙exe文件
    private void OnGUI()
    {
    
    
        if (GUI.Button(new Rect(200,100,100,100),"打开计算器"))
        {
    
    
            //判断当前运行平台是否是Windows
            if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
            {
    
    
                //判断是否是绝对路径和判断文件是否存在
                if (false == System.IO.Path.IsPathRooted(path) || System.IO.File.Exists(path))
                {
    
    
                    try
                    {
    
    
                        //打开exe文件,ie浏览器打开"http://www.baidu.com"
                        System.Diagnostics.Process.Start(path);//explorer.exe资源管理器,iexplore.exeIE浏览器
                    }
                    catch (System.Exception e)
                    {
    
    
                        Debug.Log("ExternalCallFunc exception : " + e.Message);
                    }
                }
            }
        }
    }

实现效果:
1.调用本地exe文件
在这里插入图片描述
实际上它调用外部命令时打开的是以下文件夹的exe文件:
在这里插入图片描述
像蓝牙:fsquirt.exe蓝牙exe文件、ie浏览器:iexplore.exeIE浏览器exe文件、资源管理器:explorer.exe资源管理器exe文件等这些PC平台下的都可以填写这些路径直接打开,要是自己安装的程序就不行,比如说:打开qq:System.Diagnostics.Process.Start("QQ.exe");这么写会报异常:在这里插入图片描述
提示系统找不到,必须写入完整的路径名称:System.Diagnostics.Process.Start(@"C:\Program Files (x86)\Tencent\QQ\Bin\QQ.exe");才能正常打开。
在这里插入图片描述

2、定位打开某个文件夹可以这么写:System.Diagnostics.Process.Start("D:/Program Files/Unity/");
path写入的是相对路径
在这里插入图片描述
3、调用本地ie浏览器打开某个网址:System.Diagnostics.Process.Start("https://www.csdn.net/");
在这里插入图片描述
System.Diagnostics.Process.Start()简直是有点好用呀,当然这个构造方法还有很多功能,需要的话再深入研究,可以举一反三将调用的方法封装一下,做成自己想要的效果。

猜你喜欢

转载自blog.csdn.net/qq_42437783/article/details/120288896
今日推荐