Solved

Determining which button was pressed in IE with BHO

Posted on 2006-11-10
13
812 Views
Last Modified: 2008-02-07
HI Everyone. I'm creating a BHO where I tie in to IE and then place buttons in the HTML of the page. I need to hook back in to the BHO (written in C#, .net v1.1) when my buttons are pressed. I have it working for the most part with code similar to the following :

foreach (mshtml.IHTMLElement elm in ((IHTMLElementCollection)Page.body.all))
      {
            
      if (elm.tagName.ToUpper() == "A")
                {
            if (elm.innerText == "Foo")
                      {
                             i += 1;
                   string toAdd = "<input type=\"submit\"  value=\"Do It\" id=\"YAP" + i.ToString()+ "\" />";
                             elm.insertAdjacentHTML("afterEnd",toAdd);

                   mshtml.HTMLInputElementClass MyBtn  = (mshtml.HTMLInputElementClass)Page.all.item("YAP" + i.ToString(), 0);

                   MyBtn.HTMLButtonElementEvents_Event_onclick += new mshtml.HTMLButtonElementEvents_onclickEventHandler(OnClick);



                       }

                }
}



private bool OnClick()
{
int x = 0;
return true;
}



The above code works, I can hit break points in the OnClick function when ever my buttons are clicked. The problem is I can not tell which button was clicked. The Onlick doesn't have any parameters. I need to tell which button was clicked. Any ideas? Thanks in advance. This MSHTML stuff is all really new to me.


0
Comment
Question by:minermadison
  • 7
  • 3
13 Comments
 
LVL 1

Author Comment

by:minermadison
ID: 17912521
Sorry my sample code is so sloppy,  I wish I could edit my original question.... But that first part should be in a function. Sorry.... Thanks again for any ideas.
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 17912802
You can edit your question.
Look at the questoin and then look at the links above where you would add a comment...there should be an edit link.
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 17912836
Use :

OnClick(MSHTML.IHTMLEventObj evObj){
    // then you have access to stuff like...
    evObj.srcElement.tagName;
    evObj.srcElement.id;
}
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 17912852
You mkay also need to do this :

HTMLDocumentEvents2_Event htmlEvents = (HTMLDocumentEvents2_Event)htmlDoc;
htmlEvents.onclick += new HTMLDocumentEvents2_onclickEventHandler(this.OnClick);

Utimately, although you can use your current method for handling a click on a button, the event will bubble up to the above document click event at which point you can check to see which element was clicked on and if its one you want to handle events for then do your stuff.
0
 
LVL 1

Author Comment

by:minermadison
ID: 17944982
ozymandias,
  I appreiciate your help. If I try your first suggestion I get an error saying the my onlick does not match the delegate address. If I remove the "MSHTML.IHTMLEventObj evObj" argument from my onclick function it works...

So I switched my control to an anchor (I'm adding the control to the page, and then adding an event handler, I only need to monitor events for the controls I add) becuase I can have an event handler for an achor_onlick event that takes an argument. I have tried the following three methods...


MyBtn.HTMLAnchorEvents2_Event_onclick += new mshtml.HTMLAnchorEvents2_onclickEventHandler(this.OnClick1);

+++++++++++++++++++++++++++++++++++++++++++++++++++++++

mshtml.HTMLAnchorEvents2_onclickEventHandler ev = new mshtml.HTMLAnchorEvents2_onclickEventHandler(this.OnClick1);
MyBtn.HTMLAnchorEvents2_Event_onclick += ev;

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

mshtml.HTMLAnchorEvents2_Event aevent =      (mshtml.HTMLAnchorEvents2_Event)MyBtn;
aevent.onclick += new mshtml.HTMLAnchorEvents2_onclickEventHandler(OnClick1);

In all cases my onlick1 function looks like this:
public bool OnClick1(mshtml.IHTMLEventObj obj)
{
   System.Windows.Forms.MessageBox.Show("You Clicked Button " + obj.srcElement.id);
    return true;
}



All three of these methods compile fine and never cause errors BUT I never hit my onclick event (no matter how many times I click my link)..... What am I doing wrong? Any ideas?

Also, I did try trapping the event at the document level, and that worked SOMETIMES. But it caused a lot of problems. I subscribed to the document onlick event like so...

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
mshtml.HTMLDocumentClass MyDoc = (HTMLDocumentClass)Page;
MyDoc.HTMLDocumentEvents2_Event_onclick += new mshtml.HTMLDocumentEvents2_onclickEventHandler(this.DocOnClick);
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public bool DocOnClick(mshtml.IHTMLEventObj obj)
{
System.Windows.Forms.MessageBox.Show("You Clicked Button " + obj.srcElement.id);
return true;
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

I would hit my function most of the time, but then IE would not let me do somethings, like highlight text or type in a text box. It was like IE stopped reacting to clicks after my function was recieving clicks.. And then sometimes I would not recieve the click events.... No clue - I really would appreiciate any more help. If you would like to see any more code please let me know.

Thanks
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 15

Expert Comment

by:ozymandias
ID: 17946344
OK.
This works perfectly for me.
Here is my code :

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using mshtml;

namespace winformappdemo
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            private AxSHDocVw.AxWebBrowser axWebBrowser1;
            private System.Windows.Forms.Button Button_Load;
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();
                  
                  
                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            public void LoadDoc(string path){
                  axWebBrowser1.Navigate(path);
                  mshtml.HTMLDocument htmlDoc = (mshtml.HTMLDocument)axWebBrowser1.Document;
                  HTMLDocumentEvents2_Event htmlEvents = (HTMLDocumentEvents2_Event)htmlDoc;
                  htmlEvents.onclick +=new HTMLDocumentEvents2_onclickEventHandler(htmlEvents_onclick);
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
                  this.axWebBrowser1 = new AxSHDocVw.AxWebBrowser();
                  this.Button_Load = new System.Windows.Forms.Button();
                  ((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).BeginInit();
                  this.SuspendLayout();
                  //
                  // axWebBrowser1
                  //
                  this.axWebBrowser1.Enabled = true;
                  this.axWebBrowser1.Location = new System.Drawing.Point(8, 40);
                  this.axWebBrowser1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axWebBrowser1.OcxState")));
                  this.axWebBrowser1.Size = new System.Drawing.Size(912, 528);
                  this.axWebBrowser1.TabIndex = 2;
                  //
                  // Button_Load
                  //
                  this.Button_Load.Location = new System.Drawing.Point(344, 8);
                  this.Button_Load.Name = "Button_Load";
                  this.Button_Load.TabIndex = 3;
                  this.Button_Load.Text = "Load";
                  this.Button_Load.Click += new System.EventHandler(this.Button_Load_Click);
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(928, 574);
                  this.Controls.Add(this.Button_Load);
                  this.Controls.Add(this.axWebBrowser1);
                  this.Name = "Form1";
                  this.Text = "Form1";
                  ((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).EndInit();
                  this.ResumeLayout(false);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private bool htmlEvents_onclick(IHTMLEventObj pEvtObj) {
                  System.Diagnostics.Debug.WriteLine("Item Clicked : id = " + pEvtObj.srcElement.id + " : tag = " + pEvtObj.srcElement.tagName);
                  return true;
            }

            private void Button_Load_Click(object sender, System.EventArgs e) {
                  this.LoadDoc(@"c:\temp\test.html");
            }
      }
}
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 17946353
Here is the html file I am loading :

<html>
<head>
</head>
<body>
<a name="anchor1" id="anchordid">this is an anchor</a>
</body>
</html>

When I click anywhere on the page I get this :

Item Clicked : id =  : tag = BODY

If I click on the anchor text, I get :

Item Clicked : id = anchordid : tag = A
0
 
LVL 15

Accepted Solution

by:
ozymandias earned 200 total points
ID: 17946363
I am not sure what difference it makes in here :

private bool htmlEvents_onclick(IHTMLEventObj pEvtObj) {
               System.Diagnostics.Debug.WriteLine("Item Clicked : id = " + pEvtObj.srcElement.id + " : tag = " + pEvtObj.srcElement.tagName);
               return true;
          }

whether you return true of false.
In this example it doesn't seem to make any difference.
0
 
LVL 1

Author Comment

by:minermadison
ID: 17949663
I think the main difference is that I'm not using an axWebBrowser control hosted in a form. I'm runing inside of IE, my BHO gets started everytime IE opens up a new window.

However, your code will pretty much work for me too, for recieving the docuement click events. Except, if you add a textbox to the page you will not beable to type in it, and you can not highlight text on the page, this seems to be a bug in IE. (is there similar results when using axWebBrowser control?)

So the workaround I found is to add links that go to some bogus non-existent page, then subscribe to the BeforeNavigate function. In my BeforeNav function, if I see the user is headed to this bogus page I cancel navigation, and then take my action.... seems to be working well... Thanks though for all your help...
0
 
LVL 15

Expert Comment

by:ozymandias
ID: 17949736
You're very welcome. Good luck with your project.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now