33

I'm trying to generate synthetic Javascript events in an Internet Explorer extension, and I'm having trouble getting the fromElement property to stick. Here's an excerpt of my code:

MsHtml.IHTMLDocument4 doc4 = ... // the document object
Object o = null;
MsHtml.IHTMLEventObj2 eObj = 
    (MsHtml.IHTMLEventObj2)doc4.CreateEventObject(ref o);

// string that specifies the from element, e.g. "document.getElementById('id1')":
string locator = ... 
object from = doc4.Script.GetType().InvokeMember("eval", 
                                                 BindingFlags.InvokeMethod, 
                                                 null, 
                                                 doc4.Script, 
                                                 new object[] { locator });

// from now holds a ref to an object that implements the IHTMLElement interface
eObj.fromElement = from;
IHTMLElement el = eObj.fromElement;
// el == null

What am I doing wrong here? eObj.fromElement should be equal to from, but it doesn't seem to be getting set.

Kjartan
  • 18,591
  • 15
  • 71
  • 96
Greg
  • 10,360
  • 6
  • 44
  • 67
  • 1
    Can you set it successfully in JavaScript? If so it might be simpler to just eval a javascript fragment which returns the IHTMLEventObj2 with the fromElement already set. e.g. `var o = document.createEventObject(); o.fromElement = document.getElementByID(locator); return o;` – Ben Jun 14 '12 at 11:52
  • 6
    I don't understand everything but... the `from` word is a reserved word in c#, it doesn't caused you an error? – Elwi Jul 24 '12 at 15:02
  • Are you certain that from isn't null when you do eObj.fromElement = from? You may have already checked this, but since it's not checked in the code you've given it doesn't hurt to check. It may be that eObj.fromElement is null because you've inadvertently *set* it to null. – Chris Jul 31 '12 at 15:46
  • I wouldn't use "from" for a variable name in C#. – SleepingSpider Aug 07 '12 at 21:40
  • @Elwi `from` is a conditional keyword, not a reserved word. The parser is smart enough to know when you're using it as a keyword vs an identifier. – jordanbtucker Aug 09 '12 at 06:28

2 Answers2

1

Just a wild shot in the dark but could it be because your passing a "null" object to the CreateEventObject method? What about if you change this:

Object o = null;

To this:

Object o = new Object();

On line 3 of your example?

Luke Baughan
  • 4,658
  • 3
  • 31
  • 54
1

To find the right element you should try method getElementById from IHTMLDocument6: http://msdn.microsoft.com/en-us/library/cc288667

outcoldman
  • 11,584
  • 2
  • 26
  • 30