简体   繁体   English

如何从本地 HTML 文件运行 C# 代码?

[英]How to run C# Code from a local HTML file?

I am currently re-coding my Epic-Games-Launcher-Like project in wpf (because it looked like trash in WinForm), but for making The old version i hard-coded all game pages.我目前正在 wpf 中重新编码我的 Epic-Games-Launcher-Like 项目(因为它在 WinForm 中看起来像垃圾),但是为了制作旧版本,我对所有游戏页面进行了硬编码。 I wanted to go around this by using a webBrowser which downloads a string (which is the html-code) and loads it, but now i have the problem that i dont know how to run C# Code from a HTML file.我想通过使用下载字符串(这是html代码)并加载它的webBrowser来解决这个问题,但现在我遇到的问题是我不知道如何运行Z4C4AD5FCAED07A3F74DBB1中的C#代码。 I would be happy about any kind of help.我会很高兴任何形式的帮助。

EDIT: I could also think about loading a xaml file.编辑:我还可以考虑加载 xaml 文件。

If you are actually displaying the html page in a webBrowser and the user interacts with it (as a GUI - kindda) You can build the html-page in a way that when a user clicks anything that should call external C# code - it will actually just change the url such as:如果您实际上是在 webBrowser 中显示 html 页面并且用户与其交互(作为 GUI - kindda)您可以构建 html 页面,当用户单击任何应该调用外部 C# 代码的东西时 - 它实际上会只需更改 url 如:

https://{your_url_here}/page.html#open_gta

or或者

https://{your_url_here}/page.html?open_app=gta&somemore=agrs

And write some code that will handle and detect url change, when the url is changing fetch it and check if it has a "special" url that will need an action.并编写一些代码来处理和检测 url 变化,当 url 发生变化时,获取它并检查它是否有“特殊” url 需要采取行动。 (you could switch case any option that can happen, such as open game, buy things etc..) (您可以切换任何可能发生的选项,例如打开游戏、购买东西等。)

(and direct answer - I don't think you can directly execute c# code from plain html) (直接回答 - 我认为您不能直接从纯 html 执行 c# 代码)

The current control used to display web content in a desktop application is WebView2 .当前用于在桌面应用程序中显示 web 内容的控件是WebView2 The older WebBrowser control uses Internet Explorer, which means it's incompatible with modern HTML and simply shouldn't be used.较旧的 WebBrowser 控件使用 Internet Explorer,这意味着它与现代 HTML 不兼容,根本不应该使用。

If the question is How do I talk to the host from the web page the WebView2 control's Communication between host and web content shows how to send messages from the web page to the application and vice versa.如果问题是How do I talk to the host from the web page ,WebView2 控件的主机与 web 之间的通信内容显示如何从 web 页面发送消息,反之亦然。

Sending messages to the form向表单发送消息

The web page can use the window.chrome.webview.postMessage method to send a message to the desktop application (host). web 页面可以使用window.chrome.webview.postMessage方法向桌面应用程序(主机)发送消息。 That message a can be anything that can be serialized to Json.该消息 a 可以是可以序列化为 Json 的任何内容。

The WebView2 control will raise the WebMessageReceived event when a message is posted. WebView2 控件将在发布消息时引发WebMessageReceived事件。 The event argument contains the original message as JSON but can also return it as a simple string through the TryGetWebMessageAsString事件参数包含作为 JSON 的原始消息,但也可以通过TryGetWebMessageAsString将其作为简单字符串返回

Copying from the doc examples, the following code listens to the WebMessageReceived and receives a string message from the HTML page:复制文档示例,以下代码侦听WebMessageReceived并从 HTML 页面接收字符串消息:

async void InitializeAsync()
{
    await webView.EnsureCoreWebView2Async(null);
    webView.CoreWebView2.WebMessageReceived += UpdateAddressBar;
}

void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args)
{
    String uri = args.TryGetWebMessageAsString();
    addressBar.Text = uri;
}

The web page sends this message to its host with: web 页面将此消息发送到其主机,其中包含:

window.chrome.webview.postMessage(window.document.URL);

Sending messages to the page向页面发送消息

The host can send messages to the page using the CoreWebView2.PostWebMessageAsString or CoreWebView2.PostWebMessageAsJSON methods.主机可以使用CoreWebView2.PostWebMessageAsStringCoreWebView2.PostWebMessageAsJSON方法向页面发送消息。 The web page can listen for them using window.chrome.webview.addEventListener . web 页面可以使用window.chrome.webview.addEventListener来监听它们。

Copying from the docs, the web page can listen for messages by creating an event listener when it loads, eg:从文档中复制,web 页面可以通过在加载时创建事件侦听器来侦听消息,例如:

window.chrome.webview.addEventListener('message', event => alert(event.data));

The form sends back the message it received to the web page with:该表单将收到的消息发送回 web 页面,其中包含:

void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args)
{
    String uri = args.TryGetWebMessageAsString();
    addressBar.Text = uri;
    webView.CoreWebView2.PostWebMessageAsString("Hello " + uri);
}

I made a Minecraft Launcher for Hack CLients some time ago and it had to be a C# Application, but because I wanted it to look nice and WinForm Controls are very limited, I designed a Web Application.前段时间我为 Hack CLients 制作了一个 Minecraft 启动器,它必须是 C# 应用程序,但因为我希望它看起来不错并且 WinForm 控件非常有限,所以我设计了一个 Web 应用程序。

For the WinForm I used the Nuget Package "Cefsharp Browser", in which I was able to load my HTML/PHP File.对于 WinForm,我使用了 Nuget Package “Cefsharp Browser”,我可以在其中加载我的 HTML/PHP 文件。

You can then create simple JavaScript Functions like the following:然后,您可以创建简单的 JavaScript 函数,如下所示:

    function launchClient(client) {
        mcl_desktop.test(client);
    }

    function BuyInfoMessage(){
        mcl_desktop.test("Die Kauffunktion wurde noch nicht implementiert");
    }

In C#, in Form1() you can put this Code as example在 C# 中,在 Form1() 中,您可以将此代码作为示例

            String callbackObj = "mcl_desktop";

            CefSettings settings = new CefSettings();
            Cef.Initialize(settings);
            Cef.EnableHighDPISupport();

            settings.CefCommandLineArgs.Add("disable-gpu", "1");
            settings.RemoteDebuggingPort = 8088;

            InitializeComponent();
            chromiumWebBrowser1.LoadingStateChanged += loaded;
            chromiumWebBrowser1.Load("http://localhost/mcl/");


            chromiumWebBrowser1.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
            chromiumWebBrowser1.JavascriptObjectRepository.Register(callbackObj, new Interface(), isAsync: true);

Important is the string callbackObj and the last line saying new Interface() (= new class called Interface.cs).重要的是字符串callbackObj和最后一行说new Interface() (= new class 称为 Interface.cs)。

And in this class are all defined Methods/Functions like in the Javascript part.在这个 class 中,所有定义的方法/函数都像 Javascript 部分一样。 This would be my Interface.cs这将是我的 Interface.cs

        public void BuyInfoMessage(string text, string title = "MCL")
        {
            MessageBox.Show(text, title);
        }

        public void downloadClient(string url, string filename)
        {
            using (var client = new WebClient())
            {
                client.DownloadFile(url,  filename);
            }

            if(File.Exists(localClients + "\\" + filename))
            {

            }
        }

        public void launchClient(string path)
        {
            // code to launch client
        }

It is actually pretty simple if you take some time to think about it and it is really cool如果您花一些时间考虑一下,这实际上非常简单,而且真的很酷

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM