[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Determining which button was pressed in IE with BHO

Posted on 2006-11-10
13
Medium Priority
?
877 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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
 
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 800 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

Enroll in October's Free Course of the Month

Do you work with and analyze data? Enroll in October's Course of the Month for 7+ hours of SQL training, allowing you to quickly and efficiently store or retrieve data. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …

656 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