Click here to Skip to main content
13,096,399 members (54,885 online)
Click here to Skip to main content
Articles » Languages » C# » General » Revisions
Add your own
alternative version


155 bookmarked
Posted 10 Aug 2007

How to attach to Browser Helper Object (BHO) with C# in two minutes

, 18 Feb 2011
Rate this:
Please Sign up or sign in to vote.
This article will use screen shots step by step to show beginners how to attach to BHO with C# within only two minutes
This is an old version of the currently published article.


Microsoft provided Browser Helper Object (BHO) to let developers "drive" Internet Explorer. The first BHO was introduced in 1997 with IE 4.0. I have been writing programs on BHO for months. It could be quite depressing at the very first beginning to learn all those things. Hereby, I am writing this article to help beginners like me get familiar with BHO as soon as possible.


My personal interest is actually C++. C++ programs can be a lot less memory-consuming than C# programs. But C# does provide better service on BHO comparing to C++. My first BHO program was written in C++. It took me quite a while to figure out how to handle BHO under V C++. But C# only takes me few minutes. Meanwhile, C# has lots of pleasant designs such as foreach and type conversion.


To set up a BHO Hello World Project, Lets first start a C# Class Library, as BHO is written in .dll attached to IE. You dont need a Visual Studio 2005, C# express is totally enough.

After we have this empty project, let's add one folder named BHO and an empty .csfile into the folder.

The first file has to been named IObjectWithSite to notify that this is a BHO project. To know more about this interface, please refer to

We also need to add two functions

GetSite: Gets the last site set with IObjectWithSite::SetSite. If there is no known site, the object returns a failure code.

SetSite: Provides the site's IUnknown pointer to the object.

        public interface IObjectWithSite
            int SetSite([MarshalAs(UnmanagedType.IUnknown)]object site);
            int GetSite(ref Guid guid, out IntPtr ppvSite);

Don't forget

using System.Runtime.InteropServices;

Add another .cs file named BHO.cs

Add a class called BHO in the newly added file(BHO.cs) . The class contains the interface IObjectWithSite

class BHO:IObjectWithSite

To use BHO we need to have two references, SHDocVw.dll and MSHTML.dll.You can find them at Windows\System32 folder

SHDocVw is Microsoft Shell Doc Object and Control Library

MSHTML is: All interfaces for accessing the Dynamic HTML (DHTML) Object Model are based on IDispatch and are the basis of access to the object model that is also used by scripts.

using SHDocVw;
using mshtml;
using System.Runtime.InteropServices;   
namespace BHO_HelloWorld
class BHO:IObjectWithSite


have "using SHDocVw" is not enough, you need to add references to the project.

Add SHDocVw

Later we are going to use MessageBox, we also need to add Windows Form reference

Now under BHO.cs:

we add two variables into the class, WebBrowser and HTMLDocument. Just like their name, you could easily figure out what do they do.

Besides the two methods we defined in the IObjectWithSite interface, we also need to add OnDocumentComplete. You can name the function anything you want as long as the parameters are the same as what's defined in CDHtmlDialog class. Later you need to carfully attach to an EventHandler. For the consistency of code, we name it OnDocumentComplete. OnDocumentComplete is a function of CDHtmlDialog Class . It will be triggered if the HTMLDocument downloading is complete, in other words, when your page is loaded. You can also use Navigate() or OnBeforeNavigate(). Please refer to to find out what you need exactly.

class BHO: IObjectWithSite
 WebBrowser webBrowser;
HTMLDocument document;
publiv void OnDocumentComplete(object pDisp, ref object URL)
public void SetSite(object site)
public int GetSite(ref Guid guid, out IntPtr ppvSite)


Under the IObjectWithSite.cs:

you need to point out the GUID of IE for thei program, so it can attach to IE.


    public interface IObjectWithSite
        int SetSite([MarshalAs(UnmanagedType.IUnknown)]object site);
        int GetSite(ref Guid guid, out IntPtr ppvSite);

Also, you need to assian a GUID for your own program under BHO.cs. You can use System.Guid.NewGuid() method to get one, which is really neat comparing to C++.


You cannot just leave SetSite and GetSite blank. fill them in. This step is to tell IE that the DocumentCompletent Event is attached to OnDocumentComplete in our program.

public int SetSite(object site)

        if (site != null)
            webBrowser = (WebBrowser)site;
            webBrowser.DocumentComplete +=
        new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
            webBrowser.DocumentComplete -=
        new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
            webBrowser = null;

        return 0;


    public int GetSite(ref Guid guid, out IntPtr ppvSite)
        IntPtr punk = Marshal.GetIUnknownForObject(webBrowser);
        int hr = Marshal.QueryInterface(punk, ref guid, out ppvSite);

        return hr;

Add one more reference

using Microsoft.Win32;

Under BHO.cs we need to write two functions for register/unregister of this DLL.

public static string BHOKEYNAME =
    "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects";

      public static void RegisterBHO(Type type)
          RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BHOKEYNAME, true);

          if (registryKey == null)
              registryKey = Registry.LocalMachine.CreateSubKey(BHOKEYNAME);

          string guid = type.GUID.ToString("B");
          RegistryKey ourKey = registryKey.OpenSubKey(guid);

          if (ourKey == null)
              ourKey = registryKey.CreateSubKey(guid);

          ourKey.SetValue("Alright", 1);

      public static void UnregisterBHO(Type type)
          RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BHOKEYNAME, true);
          string guid = type.GUID.ToString("B");

          if (registryKey != null)
              registryKey.DeleteSubKey(guid, false);

Now compile, under your release folder, you will find the .dll of your own project.

Then, use regasm /codebase "BHO HelloWorld.dll" to register our dll. We got a problem here. The REGASM told me it's not registerd. WHY?

Because we didn't set the BHO class as public. That's why.

public class BHO:IObjectWiteSite

now, do it again. It's successful.

open your registry. Find out Browser Helper Object under LOCAL_MACHINE->SOFTWARE->MICROSOFT->WINDOWS->EXPLORER

So, now program has been officially attached to your BHO. We need to fillin the OnDocumentComplete function. It's really neat to use C#'s foreach loop rather than for loop in C++. So you won't need to care about the indexer. We will also see the type conversion is quite easy. This is an example on we want to find out the NAME attributes of an IHTMLInputElement.

An IHTMLInputElement is an Input element on HTML Page.

If the IHTMLInputElement does not have name attributes, we will fetch the ID attribute. Then pop up the value.

    public void OnDocumentComplete(object pDisp, ref object URL)

        document = (HTMLDocument)webBrowser.Document;

        foreach (
            IHTMLInputElement tempElement in document.getElementsByTagName("INPUT"))
      !=null?"it sucks, no name, try id"+

There you go, see?

Now, let's try using BeforeNavigate()2.

As we can see, there are BeforeNavigate and BeforeNavigate2(). We go for the latter one. If you are interested, you can use the first one.

Add the function prototype.

public void OnBeforeNavigate2(object pDisp, ref object URL, ref object Flags,
    ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)

Set up the hook.

public int SetSite(object site)

        if (site != null)
            webBrowser = (WebBrowser)site;
            webBrowser.DocumentComplete +=
            new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
               new DWebBrowserEvents2_BeforeNavigate2EventHandler(this.OnBeforeNavigate2);
            webBrowser.DocumentComplete -=
              new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
            webBrowser.BeforeNavigate2 -=
              new DWebBrowserEvents2_BeforeNavigate2EventHandler(this.OnBeforeNavigate2);
            webBrowser = null;

        return 0;


Now, we want to steal the passwords on an Input Password element

public void OnBeforeNavigate2(object pDisp, ref object URL, ref object Flags,
    ref object TargetFrameName, ref object PostData, ref object Headers,
    ref bool Cancel)
        document = (HTMLDocument)webBrowser.Document;

        foreach(IHTMLInputElement tempElement in document.getElementsByTagName("INPUT"))




See, how easily, you can get it.


In conclusion, its really easy to handle BHO with C#. Thats why many there are so many IE add-ons. I hope these are useful to you. To save your time, you can use the project template I made. Download it and put it under your Visual Studio 2005\Templates\ProjectTemplates folder (its usually under My Document).


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Web Developer Horizon Ideas
United States United States
My name is Jia Chen and I want you tell you about my childhood dream: being a problem-solver. My mom told me it was silly because it wasn't really a profession. Through the last decade, I have been a software engineer, a product manager, a repetitive student, a management consult and an entrepreneur. They appear far from my childhood dream. But I still think I am living it. Because the essence of it is to find problems and solve problems. Some times I may not solve new problems, but I always want to solve old problems in a new way.

You may also be interested in...


Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.
QuestionIE Extension not running Pin
Member 1020116326-Feb-16 23:06
memberMember 1020116326-Feb-16 23:06 
AnswerRe: IE Extension not running Pin
Member 1267135316-Aug-16 21:55
memberMember 1267135316-Aug-16 21:55 
QuestionPre event of DocumentComplete Pin
maitrey68421-Apr-15 21:12
professionalmaitrey68421-Apr-15 21:12 
QuestionBHO not working for me Pin
roshraj135721-Apr-15 19:28
memberroshraj135721-Apr-15 19:28 
Questionproject template Pin
grayaznalli1122-Sep-14 18:16
membergrayaznalli1122-Sep-14 18:16 
QuestionBHO is not working for me Pin
maamangala15-May-14 0:36
membermaamangala15-May-14 0:36 
QuestionThisWorked Pin
Member 107421917-May-14 1:06
memberMember 107421917-May-14 1:06 
QuestionBHO doesn't work Pin
Member 1074219129-Apr-14 1:51
memberMember 1074219129-Apr-14 1:51 
GeneralMy vote of 5 Pin
Sean Tosh14-Mar-14 9:41
memberSean Tosh14-Mar-14 9:41 
Question运行时被阻止 Pin
zailushang31-Jul-12 15:35
memberzailushang31-Jul-12 15:35 
Questionregasm problem Pin
super sheep25-Jun-12 17:51
membersuper sheep25-Jun-12 17:51 
Question2nd time fails to run Pin
Pathaksa Tongpitak1-Jun-12 2:53
memberPathaksa Tongpitak1-Jun-12 2:53 
QuestionWorking in IE9? Pin
Pathaksa Tongpitak31-May-12 2:08
memberPathaksa Tongpitak31-May-12 2:08 
QuestionHow can I run my code after the user input URL and click "goto" Pin
Super Savage4-Apr-12 4:04
memberSuper Savage4-Apr-12 4:04 
QuestionIE crashes when new tab is opened Pin
dub.tribe19-Sep-11 10:10
memberdub.tribe19-Sep-11 10:10 
QuestionRE: cause IE 8 open url forever with blank page sometimes Pin
Member 219681618-Oct-10 6:37
memberMember 219681618-Oct-10 6:37 
GeneralEvent track Pin
sdfshjkf3-Aug-10 6:40
membersdfshjkf3-Aug-10 6:40 
GeneralWindows 7 & IE 8 Pin
bray8-Jun-10 9:43
memberbray8-Jun-10 9:43 
GeneralRe: Windows 7 & IE 8 Pin
firehawk3-Feb-11 14:05
memberfirehawk3-Feb-11 14:05 
GeneralFollowup question on this article Pin
Tushar Trivedi25-Mar-10 3:16
memberTushar Trivedi25-Mar-10 3:16 
GeneralRe: Followup question on this article Pin
Jia.C25-Mar-10 6:56
memberJia.C25-Mar-10 6:56 
GeneralBHO to display area scrolled Pin
codeprojectuser201010-Jan-10 23:27
membercodeprojectuser201010-Jan-10 23:27 
GeneralRegarding your BHO Pin
Vishal_00730-Nov-09 7:00
memberVishal_00730-Nov-09 7:00 
QuestionHow get instance of tollbar Pin
ramveers17-Sep-09 22:24
memberramveers17-Sep-09 22:24 
QuestionHow can I call function in C# BHO through Javascript Pin
hjzhu1-Sep-09 20:58
memberhjzhu1-Sep-09 20:58 
QuestionHow can I accecc c# bho method from javascript Pin
hjzhu31-Aug-09 20:56
memberhjzhu31-Aug-09 20:56 
Questionhow link the my program with email by c# ? Pin
salemmohamed9-Aug-09 18:59
membersalemmohamed9-Aug-09 18:59 
GeneralException from HRESULT: 0x80040200 Pin
Boaz Feldbaum20-Jul-09 21:55
memberBoaz Feldbaum20-Jul-09 21:55 
Generaldeployment Pin
thebrim20-Jul-09 4:03
memberthebrim20-Jul-09 4:03 
Generaldeployment Pin
thebrim13-Jul-09 4:34
memberthebrim13-Jul-09 4:34 
GeneralRegarding your BHO Pin
Member 253878022-Jun-09 9:04
memberMember 253878022-Jun-09 9:04 
GeneralRe: Regarding your BHO Pin
elbertlev10-Aug-09 20:42
memberelbertlev10-Aug-09 20:42 
GeneralRe: Regarding your BHO Pin
Vishal_00730-Nov-09 1:10
memberVishal_00730-Nov-09 1:10 
QuestionFirefox Pin
vanila2319-Jun-09 7:22
membervanila2319-Jun-09 7:22 
QuestionControling the execution of JScript Code in IE Pin
asahin910-Jun-09 13:57
memberasahin910-Jun-09 13:57 
AnswerRe: Controling the execution of JScript Code in IE Pin
AlexTiffy11-Nov-09 19:05
memberAlexTiffy11-Nov-09 19:05 
GeneralCorrections on article. Pin
xzz019517-Mar-09 4:23
memberxzz019517-Mar-09 4:23 
QuestionHow to solve delay in display of replaced text on a web page? How to reduce CPU usage which is caused due to 'foreach loop'? Pin
svt gdwl29-Jan-09 18:41
membersvt gdwl29-Jan-09 18:41 
AnswerRe: How to solve delay in display of replaced text on a web page? How to reduce CPU usage which is caused due to 'foreach loop'? Pin
HUMPPAAA!26-Mar-09 5:11
memberHUMPPAAA!26-Mar-09 5:11 
GeneralIf page opens in a iframe then how to access the contents/tags of iframe Pin
harshkapoors20-Jan-09 4:44
memberharshkapoors20-Jan-09 4:44 
GeneralRe: If page opens in a iframe then how to access the contents/tags of iframe Pin
svt gdwl20-Jan-09 18:45
membersvt gdwl20-Jan-09 18:45 
Generalmscoree.dll Pin
tr4nc313-Jan-09 19:44
membertr4nc313-Jan-09 19:44 
QuestionHow to reduce CPU usage when the dll is registered? Pin
abhi11shukla6-Jan-09 21:35
memberabhi11shukla6-Jan-09 21:35 
Questionhow to debug? Pin
Maverickcool4-Jan-09 2:10
memberMaverickcool4-Jan-09 2:10 
AnswerRe: how to debug? Pin
Boaz Feldbaum20-Jul-09 21:46
memberBoaz Feldbaum20-Jul-09 21:46 
QuestionHow to catch when user clicks on a link in internet explorer? Pin
jan150311-Dec-08 23:31
memberjan150311-Dec-08 23:31 
GeneralBHO gets loaded also in Windows Explorer Pin
MatteoSp12-Oct-08 23:52
memberMatteoSp12-Oct-08 23:52 
GeneralRe: BHO gets loaded also in Windows Explorer Pin
MatteoSp13-Oct-08 3:24
memberMatteoSp13-Oct-08 3:24 
QuestionI am wondering if I can access the cookies of IE by using BHO? Pin
Lee Jenkins10-Sep-08 15:23
memberLee Jenkins10-Sep-08 15:23 
AnswerRe: I am wondering if I can access the cookies of IE by using BHO? Pin
tsahiB27-Feb-09 4:39
membertsahiB27-Feb-09 4:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170813.1 | Last Updated 18 Feb 2011
Article Copyright 2007 by Jia.Chen
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid