我在C#Winform中创建了一个像程序启动器一样的蒸汽,而我正在使用HTML和Gecko 我想知道是否可以添加我自己的javascript或onclick()函数并将其连接到我的Windows Form C#app中,例如,我需要在按钮(HTML)中添加一个函数来激活启动程序的c#中的函数(它是一个获取应用程序名称并启动该应用程序的功能)。
这个example显示了两种不同的方式,可以从javascript到C#进行通信。
location
并使用C#处理和取消导航。示例HTML:
<html>
<body>
</body>
<script type='text/javascript'>
/* Begin (Hatton) method of communicating from javascript to C# */
alert('javascript : about call message C# (Hatton) method');
event = document.createEvent('MessageEvent');
var origin = window.location.protocol + '//' + window.location.host;
event.initMessageEvent ('callMe', true, true, 'some data', origin, 1234, window, null);
document.dispatchEvent (event);
alert('javascript : message sent to C# (Hatton) method');
/* End (Hatton) method of communicating from javascript to C# */
/* Begin javascript changing location.href method */
alert('javascript : about call message C# location changed method');
location.href='http://somehost//someevent.php?somedata';
alert('javascript : message sent to C# location changed method');
/* End javascript changing location.href method */
</script>
</html>
Example.cs代码:
using System;
using System.IO;
using System.Windows.Forms;
using Gecko;
namespace Example6
{
static class Example6
{
private static GeckoWebBrowser _browser;
[STAThread]
static void Main()
{
// Don't use XULRunnerLocator.GetXULRunnerLocation() in production software.
string firefox14Path = XULRunnerLocator.GetXULRunnerLocation();
Xpcom.Initialize(firefox14Path);
var form = new Form();
_browser = new GeckoWebBrowser { Dock = DockStyle.Fill };
_browser.Navigating += InstallCustomEventListener;
_browser.Navigating += ListenForFakeNavigationMessages;
_browser.Navigate("file://" + Path.Combine(Environment.CurrentDirectory, "Example6.html"));
form.Controls.Add(_browser);
Application.Run(form);
}
#region Hatton method
static void InstallCustomEventListener(object sender, GeckoNavigatingEventArgs e)
{
_browser.Navigating -= InstallCustomEventListener;
_browser.AddMessageEventListener("callMe", ((string p) =>
MessageBox.Show(String.Format("C# : Got Message '{0}' from javascript", p))));
}
#endregion
#region location changed method
static void ListenForFakeNavigationMessages(object sender, GeckoNavigatingEventArgs e)
{
const string id = "http://somehost//someevent.php?";
var uri = e.Uri.AbsoluteUri;
if (uri.Contains(id))
{
MessageBox.Show(String.Format("C# : Got Message '{0}' from javascscript", uri.Substring(id.Length)));
// This is a fake navigating event - cancel it.
e.Cancel = true;
}
}
#endregion
}
}
还可以看看example 4。