微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

新发的无聊小发明——PC端自制迷你浏览器给Unity调用Windows窗体应用/WebBrowser/EXE

一、前言

Unity本身提供了打开外部浏览器的方法

Application.OpenURL("https://blog.csdn.net/linxinfa");

但有些情况,可能不想使用外部浏览器。在PC端,有一些第三方库实现了浏览器功能,但是库文件非常大,可以参见我之前这篇文章《Unity内嵌浏览器插件(Android、iOS、Windows)》

能否利用WindowsAPI自制一个迷你浏览器呢?
本文我就教你通过Windows窗体应用工程来实现迷你浏览器功能

原理如下

在这里插入图片描述


最终效果

在这里插入图片描述

二、制作C# Windows窗体应用,实现浏览器功能

1、创建工程

创建Windows窗体应用(.NET Framework)。

在这里插入图片描述

2、Webbrowser控件

添加Webbrowser控件。

在这里插入图片描述


然后调用Navigate接口,参数就是url

this.webbrowser1.Navigate("https://blog.csdn.net/linxinfa");

3、接收命令行参数

由于我们的这个窗体程序是要给Unity调用的,所以需要接收命令行参数。
修改Program.cs添加args并传给Form1

static class Program
{
    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        if (args.Length == 0)
            Application.Run(new Form1());
        else
            Application.Run(new Form1(args));
    }
}

Form1.cs中,实现两个构造函数

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.Text = "内置浏览器";
        this.webbrowser1.Navigate("https://blog.csdn.net/linxinfa");
    }


    public Form1(string[] args)
    {
        InitializeComponent();
        this.Text = "内置浏览器";
        //命令含参数
        string url = args[0];
        this.webbrowser1.Navigate(url);
    }
}

4、启动,测试

点击启动,测试正常。

在这里插入图片描述

5、发布Release版exe

解决方案选择Release

在这里插入图片描述


点击生成解决方

在这里插入图片描述


即可在工程目录中bin/Release生成exe文件,只有9KB,不错。

在这里插入图片描述

6、命令行传参测试

通过命令行启动exe,并传递参数www.baidu.com,如下,可以正常显示

在这里插入图片描述

7、工程下载

我已把上面的这个Demo上传CODE CHINA,感兴趣的同学可以下载下来学习。
地址:https://codechina.csdn.net/linxinfa/windows-mini-webbrowser
如果你只是纯粹想下载exe,可以直接点这个链接https://codechina.csdn.net/linxinfa/windows-mini-webbrowser/-/raw/master/winform_webbrowser/bin/Release/winform_webbrowser.exe

三、Unity调用浏览器exe

1、拷贝exe到Unity工程

将上面的exe拷贝到Unity工程中的StreamingAssets目录。

在这里插入图片描述

2、在C#中启动exe

制作个简单的按钮UI,创建一个Main.cs脚本,挂到Canvas上,绑定按钮。

在这里插入图片描述


Main.cs代码如下

using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Diagnostics;

public class Main : MonoBehavIoUr
{
    public Button browserBtn;

    // Start is called before the first frame update
    void Start()
    {
    	//按钮被点击
        browserBtn.onClick.AddListener(() =>
        {
        	//exe路径
            var exePath = Path.Combine(Application.streamingAssetsPath, "winform_webbrowser.exe");
            //打开迷你浏览器exe,参数是url
            string url = "https://blog.csdn.net/linxinfa";
            Process pro = Process.Start(exePath, url);
            /*
            pro.WaitForExit();
            int Result = pro.ExitCode;  //exe退出回传值
            if (Result == 1)//接收到exe退出代码"1"
            {
                
            }
            */
        });
    }
}

3、运行Unity测试

运行Unity调用迷你浏览器exe成功。

在这里插入图片描述

四、补充,浏览器c#与js代码交互

有没有办法实现c#与js代码交互呢?有。例子如下:
c#代码如下

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
 
namespace WinFormPractice
{
	//注意要加ComVisible,否则会编译失败
    [ComVisible(true)]
    public partial class FormbrowserJs : Form
    {
        public FormbrowserJs()
        {
            InitializeComponent();
 			//访问html
            webbrowser.Navigate(Path.Combine(Application.StartupPath, "HTMLbrowserJs.html"));
            //注册监听
            webbrowser.ObjectForScripting = this;
        }
 
 		//js调用c#
        public void ShowMsgForJs(string msg)
        {
            infoLabel.Text += $"{msg}\r\n";
        }
 
 		//c#调用js
        private void BtnSend_Click(object sender, EventArgs e)
        {
        	try
        	{
        		webbrowser.Document.InvokeScript("ShowMsgForCSharp", new []{ "hello world" });
        	}
            catch(Exception ex)
            {
            	Console.WriteLine(ex);
			}
        }
    }
}

HTMLbrowserJs.html代码如下

<!DOCTYPE html>
  
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <Meta charset="utf-8" />
    <title></title>
    <script>
        //alert ("准备就绪");
        window.external.ShowMsgForJs("准备就绪");
  
        function ShowMsgForCSharp(str) {
            var msg = "收到消息:" + str;
  
            //1、调用 C# 方法
            window.external.ShowMsgForJs(msg);
            //2、改变网页内容
            document.getElementById("info").innerHTML += msg + "<br/>";
            //3、弹窗;
            alert(msg);
        }
    </script>
</head>
<body>
    <div> 通过 Webbrowser 让 JS 与 C# 代码交互 测试页 </div>
    <div id="info"></div>
</body>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐