问题
I am able to call C# methods of WebBrowser.ObjectForScripting with javascript window.external from WebBrowser WinForms control and pass string, int, bool etc. However I don't know how to pass javascript Date object and somehow convert/marshal it to .NET DateTime class.
Obviously, I could pass a string and parse it, but this is really not the point. I'm just curious how could I do it with javascript Date and .NET DateTime?
回答1:
You can take advantage of the fact that dates in Javascript are expressed as the number of milliseconds elapsed since the UNIX epoch (1970-01-01 00:00:00 UTC). Use the valueOf() method to obtain that value from a Date object :
var millisecondsSinceEpoch = yourDate.valueOf();
If you can marshal that value to C# as a double, you can create the appropriate DateTime object using its constructor and the AddMilliseconds() method:
DateTime yourDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(millisecondsSinceEpoch);
回答2:
I found better solution for my project.
in javascript:
var date = new Date();
myComObject.DoSomething(date.getVarDate());
in C#
[ComVisible(true)]
public class Foo
{
public void Bar(DateTime dateTime)
{
Console.WriteLine(dateTime);
}
}
回答3:
I finally got it working. I don't know why, but I am unable to use it with dynamic. Here is the solution:
[ComVisible(true)]
public class Foo
{
public void Bar(object o)
{
var dateTime = (DateTime)o.GetType().InvokeMember("getVarDate", BindingFlags.InvokeMethod, null, o, null);
Console.WriteLine(dateTime);
}
}
来源:https://stackoverflow.com/questions/5662128/passing-javascript-date-object-to-c-sharp-webbrowser-control-using-window-extern