Click here to Skip to main content
Click here to Skip to main content

Automating Internet Explorer

By , 24 Feb 2005
 

Introduction

I attended an ASP.NET Users Group meeting and saw a presentation given by Demetrie Gerodimos. He is an Architect at Dell and was giving a presentation on Test Driven Development. An interesting point of his presentation for me was when he explained how they execute their tests. A discussion with him after the meeting revealed that they were automating Internet Explorer to test their ASPX pages.

After spending some time researching how easily you can automate Internet Explorer in C# (with the help of some URLs given to me by Demetrie), I began writing my own version of IEDriver. The URLs I looked at had a basic example of how to instruct IE to perform various actions. Over the course of the last year, I have enhanced my IEDriver class to handle other types of interactions with IE that I have required. While this is by no means a complete automation class, I believe it performs many of the common functions needed when writing automated tests.

Background

The basic idea here is that we will use Interop services to invoke methods on the COM interfaces built into Internet Explorer. I have written this article because the documentation available on these interfaces is scarce at best. I have spent a lot of time researching on the web and doing trial and error experimentation with these interfaces to produce much of this IEDriver class.

Using the code

The gist of it is a class called IEDriver. This class' constructor will create a new IEXPLORE.EXE process and attach to it. From then on, the methods on the IEDriver class can be used to simulate a user using his browser. While I have not implemented every type of interaction you could have with your browser, I have implemented most of the routines that I have needed to write automated tests for my product.

I have tried to hide the inner workings of the driver from the user of the class. You will notice that there are ClickXXX methods and GetXXX values that will deal with all the COM interfaces to perform the actions necessary or return the value you are interested in.

Here is an example of how easy this class is to use. This example will simply navigate to Google and search for "Automating Internet Explorer":

IEDriver driver = new IEDriver();
driver.Navigate("http://www.google.com");
driver.SetInputStringValue("q", "Internet Explorer Automation");
driver.ClickButton("btnG");

In this example, "q" is the name of the input control and "btnG" is the name of the button control on the Google page. Preferably, you will have ID attributes on your HTML elements, but if there is no ID attribute, the driver will find the element with a name attribute.

In order to use this code, you will need to do a couple of things. First of all, you will need to add a couple of references to your project. To do this, right click on References and click Add Reference:

Right click references and select Add Reference

When the Add Reference dialog comes up, first select the .NET tab. Scroll down to the Microsoft.MSHtml object, and click the Select button.

Select the Microsoft.mshtml .Net object

Next, click on the COM tab. Scroll down to the Microsoft Internet Controls object and click the Select button.

Select the Microsoft Internet Controls COM object

Now click on OK. This will add the necessary references to your project that will allow IEDriver class to make the necessary calls to automate IE.

Once you have added the appropriate references to your project, just include the IEDriver in your project. Now, all you have to do is import the IEAutomation namespace into your class and you can begin writing automated tests using IE.

Points of Interest

One thing to keep in mind. The documentation on this stuff is not very good so if you need to enhance IEDriver to support a feature that it currently doesn't, your best bet is probably to use your intellisense to invoke a method that you think might do what you want, and assign the variable to some temporary local variable. Then, fire up your debugger and use the watch window to find out all you can about the objects returned.

Tips

While writing my own automated tests, I have discovered that it is useful to extend the IEDriver class and add methods that do tasks that I might perform quite often so that I can use the intellisense and the compiler to eliminate the possibility of mistyping control names. For example:

class MyIEDriver : IEDriver {
    public void ClickSave() {
        ClickButton("SaveButton");
    }
}

This gives you compiler checking for things that may normally only be caught at runtime.

History

  • 2-23-2005: Initial release.

Other Articles

Writing Automated Tests With NUnit and IE.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Leslie Hanks
Web Developer
United States United States
Member
A developer for ScienceTRAX, LLC
 
Web: www.codeoutlaw.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionSetting Zoommemberclosl24 Sep '12 - 8:46 
Thank you for your work! It's very helpful!
 
How can I set the Zoom to 100%.... Our tests fail if it's anything but 100%
SuggestionThread.Sleep(500); errormemberdonneverdies20 Jul '12 - 23:16 
this causing error because IE takes different time to load up i mean if IE is already open it will take less time or if IE is not open it will take long time.. so no fix time tht how much time thread should sleep so i got a solution for it
just change..
 
Process m_Proc = Process.Start("IExplore.exe"); to
Process m_Proc = Process.Start("IExplore.exe", "-nomerge www.google.com");
and Thread.Sleep(500) to Thread.Sleep(5000)
 
so now it will open new IE in new browser and will wait 5 sec to get it complete ...
 
it helped me hope it helps all... Smile | :)
Questioninvalid cast exceptionmembermani224628 Apr '12 - 2:35 
i get this error when i run the code.
 
System.InvalidCastException was unhandled
Message=Specified cast is not valid.
Source=Interop.SHDocVw

 
on this line
if(Browser.HWND == (int)m_Proc.MainWindowHandle)

kindly help
GeneralThank youmemberRavi Vooda10 Apr '12 - 1:27 
Smile | :) it helped a lot
Questionhow to click button if button has no ID and no Name and just valuememberMustangU12 Nov '10 - 2:48 
how to click button if button has no ID and no Name and just value
 
say example ::
 
<INPUT TYPE="SUBMIT" VALUE="Login" TABINDEX=4>;
 
here button has no name and no ID.
 
it has just value.
 
any help appriciated.
 
Regards,
Chetan..
GeneralInternet Explorer 8 resolutionmemberprosh0t13 May '10 - 7:55 
IE 8 introduces something called "Loosely Coupled IE" (LCIE), which launches extra processes for use in additional tabs and such. If you try to use this code and launch an IE window after an existing one is already open this code will not work. When attempting to spawn the new process and navigate to a page, it pops up with the error 'Process has exited, so the requested information is not available.' I had to resolve this by changing a registry setting
 
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main
 
then add TabProcGrowth as a new DWord 32 bit value, and set it to '0'. Restart all instances of IE. It should work after that and you can open subsequent IE processes at any time, no matter how many previous ones are open.
 
Hopefully this will help someone else.
GeneralRe: Internet Explorer 8 resolutionmembermartho21 Jul '10 - 5:39 
Thanks, this helped a lot!
GeneralSmall ModificationmemberAshrafur Rahaman2 Mar '10 - 7:19 
That article really helped me a lot. I was facing problem to insert data in the text box and click button. It worked fine in my local computer where VS is installed but for the computers where VS is not installed it shown exception to convert _Comobject to mshtml.HTMLInputElementClass.
 
So I modified a bit. here is the modified file http://www.box.net/shared/zymkn7x5yv
 
Anyway thanks a lot for the article.
Ashrafur Rahaman

GeneralGreat!! ThanksmemberAshrafur Rahaman1 Mar '10 - 9:07 
Thanks.
Save a lot of my time Smile | :)
Ashrafur Rahaman

GeneralSelectively Disabling ContentmemberKevin Yochum21 Feb '10 - 15:40 
I have my code to automate IE working, but it could be made faster by eliminating all of the extraneous downloading - images, JavaScript, Flash advertisements, etc. Is there a way to disable some or all of these items on an instance by instance basis? For example, for project 1, disable images and flash and for Project 2, disable JavaScript and flash? So far, all of my attempts to do so enable images for example in all browser sessions - even those that are not automated. (It changes all Internet Explorer options globally.)
 
Thanks!
GeneralProblem with running in IE 7+memberHessam Abbasi10 Apr '09 - 0:19 
First thank you for this useful article.
I have a problem in working with IE 7 +. My program does not work in IE 7. Is it normal?
So what should we do in IE 7?(For example IE 7 has multiple tabs, how to select one tab, do i need another dll?)
QuestionRe: Problem with running in IE 7+memberMember 32368633 Jun '09 - 16:50 
I am confused by the same problem. Anyone can help??
AnswerRe: Problem with running in IE 7+memberbigheart00117 Jan '10 - 18:03 
the core mshtml.dll maybe different
 
hope you can find the reason
 
I want to make one
 
if success ,I will share it to all you.
GeneralRe: Problem with running in IE 7+memberdaihugo26 Mar '10 - 16:08 
I test the code above and found the same problem.
The way to solve this is to change code below
 
Process m_Proc = Process.Start("IExplore.exe");
 
Thread.Sleep(500); to Thread.Sleep(3000);
 
Maybe it's because the ie hadn't load. So we need to wait longer.
 
There is also some way to test whether the ie has loaded.
Whoever interested please read the article:
http://www.colblog.net/node/205
GeneralRe: Problem with running in IE 7+memberBassem Zeft28 Jun '10 - 6:33 
God bless you all, this information helped me a lot
GeneralGetElementByValueOncememberNoname_vn1 Dec '08 - 3:10 
Hi,
 
I think you should replace the following line (bolded text)
 
private IHTMLElement GetElementByValueOnce(string tagName, string elementValue)
{
    HTMLDocument document = ((HTMLDocument)IE.Document);
    IHTMLElementCollection tags = document.getElementsByTagName(tagName);
 
    IEnumerator enumerator = tags.GetEnumerator();
 
    while (enumerator.MoveNext())
    {
        IHTMLElement element = (IHTMLElement)enumerator.Current;
        if (element.innerText == elementValue)
        {
            return element;
        }
    }
 
    return null;
}
 
with this
 
private IHTMLElement GetElementByValueOnce(string tagName, string elementValue) {
	HTMLDocument document = ((HTMLDocument) IE.Document);
	IHTMLElementCollection tags = document.getElementsByTagName(tagName);
 
        IEnumerator enumerator = tags.GetEnumerator();
 
	while (enumerator.MoveNext()) {
		IHTMLElement element = (IHTMLElement) enumerator.Current;
                if (element.getAttribute("Value", 0).ToString().Equals(elementValue)) {
			return element;
		}
	}
    
	return null;
}
 
Noname_vn
QuestionExcellent - can the update for class constructor as previously posted be added to the source code?memberMember 47604192 May '08 - 13:04 
Also,
 
Another possible method
 
public void FormSubmit(string formID)
{
mshtml.IHTMLFormElement form = (mshtml.IHTMLFormElement)GetElementById(formID);
isDocumentComplete = false;
form.submit();
WaitForComplete();
}
GeneralIE7 supportmemberDvir13 Feb '08 - 4:09 
Hi,
It is working fine in IE6
but in IE7 it is not opening the new I Frown | :( Explorer window
GeneralCool!memberDev1238 Jan '08 - 13:25 
Try this scripting tool
http://ieautomation.freewebpage.org[^]
 
Poke tongue | ;-P
AnswerRe: Cool!membersoptest14 May '08 - 9:10 
actually it's been moved to
http://mytextreader.com/ieautomation/index.htm[^]
 
-Mikhail

Generalgreatmemberppcode12 Dec '07 - 22:38 
It's great,thx
 
my blog:
http://blog.ppcode.com

QuestionHow to autoprintmemberNguoi Lap Trinh22 Nov '07 - 18:40 
i want to automatic print a webpage. With this technology. how can i do that ?
Thank in advance Rose | [Rose]
AnswerRe: How to autoprintmemberAlex Furman26 Nov '07 - 13:35 
It can be easily done with SWExplorerAutomation (SWEA) from http://webius.net.
 
The print code example using SWEA:
 
public static void explorerManager_DialogActivated(object sender, SWExplorerAutomation.Client.DialogScene dialogScene) {
if (dialogScene.Title == "Print") {
if (dialogScene.ControlExists("Print"))
dialogScene.DialogButton(("Print")).Click();
}

public static void Main() {
ExplorerManager explorerManager = new ExplorerManager();
SWExplorerAutomation.Client.Scene scene;
explorerManager.DialogActivated += new SWExplorerAutomation.Client.DialogActivatedEventHandler (SWExplorerAutomationExamples.CodeTemplate.explorerManager_DialogActivated);
explorerManager.LoadProject("..\\..\\PrintDialog.htp");
explorerManager.Connect();
explorerManager.Navigate("http://webiussoft.com/");
scene = explorerManager["Scene_0"];
scene.WaitForActive(30000);
scene.HtmlContent("HtmlContent_0").Invoke("window.print();",ControlActionType.InvokePageScript);
explorerManager.DisconnectAndClose();
}

 
AlexF

GeneralRe: How to autoprintmemberNguoi Lap Trinh26 Nov '07 - 15:26 
SWExplorerAutomation....but it isn't free Cry | :(( --> i just want to know the technology autoprint so i can do it myselfUnsure | :~
GeneralRe: How to autoprintmembermartho21 Jul '10 - 5:41 
You can print to the default-printer by using:
Object em = null;
driver.IE.ExecWB(SHDocVw.OLECMDID.OLECMDID_PRINT,
		SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER,
		ref em, ref em);
 
(Just make IE public in IEDriver or add a function to IEDriver itself).
GeneralRe: How to autoprintmemberPavan Nagumalli19 Jul '12 - 0:11 
How about number of copies??
GeneralAnother solutionmemberMorningkill9 Nov '07 - 6:06 
This code is very good, but it's not fully featured (that's not a critic, just a fact). For example, it does not have an option to close the IE opened.
I found that :
http://watin.sourceforge.net/
It's free, opensource, and still supported.
 

GeneralRe: Another solutionmemberZaunCPP28 Oct '08 - 11:04 
Watin does not support Firefox, or has this changed meanwhile?
GeneralRe: Another solutionmemberMorningkill28 Oct '08 - 20:58 
Yes, I don't think watin supports FF.
 
The point of Watin is, I think, to run automated tests which are not depending on the browser used to fail or not.
 
There was a mozilla activeX, but I never got far with it. The one I can found seems to be abandoned http://www.iol.ie/~locka/mozilla/mozilla.htm[^]
GeneralWeb Testing Integrated With Visual StudiomemberFrederic Torres7 Oct '07 - 10:11 
For more advanced alternative and integrated with Visual Studio,
Look InCisif.net and their main screen cast.

 
F.Torres

QuestionHow to automate security alertmemberdvenkat3 Sep '07 - 2:12 
When i click on the login button on the page, which i am trying to automate. I am getting a security alert dialog, how to automate this?.
AnswerRe: How to automate security alertmemberFrederic Torres7 Oct '07 - 10:03 
InCisif.net is a functional web testing for the .NET languages which also support JavaScript and Windows system dialog like the security alert, file download, user login...
www.InCisif.net
 
Frederic Torres
www.InCisif.net
Web Testing With C# Or VB.NET

QuestionRunning the code from web servermemberatul.pioneers18 Aug '07 - 2:04 
Hi,
 
I am trying to use this code for some application of mine. However, this code works fine, if I run it on my local server, through the same machine. However, when I load this on my remote web-server and try to access through http, it throws an error and does not open the explorer. Can anybody help or provide me a patch.
 
Thanks
Atul Jain
AnswerRe: Running the code from web servermemberAlex Furman7 Nov '07 - 15:30 
IE requires an user profile to be loaded. The Web server user account doesn't have an user profile.
You can try SWExplorerAutomation (SWEA) from http://webius.net. SWEA allows to run IE under user account different from Web server account.
 
AlexF

QuestionNullReferenceException Error in VS 2005memberCyborgcom5 Jul '07 - 12:16 
I have used this tool with VS2003 and now I am trying to upgrade to VS2005, but now I get this error every time the IEDriver constructor executes.
What it seams is that the foreach loop does not finds the WindowHandel index value matching the Browser.HWND. At the end of loop the _IE variable will never be instantiated. Can you give me any advise in how to work this problem.
AnswerRe: NullReferenceException Error in VS 2005memberRbearl2 Sep '09 - 11:31 
I encountered the same problem in VS 2008 and resolved it by increasing the sleep period in the constructor.
GeneralFrames Security, and NormailzationmemberTriLogic27 May '07 - 6:11 
I have a severe problem with frames and security.
 
When I try to access the document in a given frame I get a security exception. I get this exception under the Visual Studio debugger for every property of a frame. I'd like to be able to solve this problem right away --- because ---
 
I have a substatial amount of code written called DomDriver which sits over the top of IEDriver and allows you to drive IEDriver in many more ways than the original code provides. For instance I have methods that allow you to click an anchor or button based on the value of one of it's attributes, or based upon the innerHTML, outHTML or text - exact match, contains, begins with and ends with. Lookup and element using the same methods.
 
I also have incorporated code to capture an existing window (someone else's code project) into this project. You can also retrict the element lookups to a single frame and / or frameset.
 
If anyone knows how to get around the frames + security problem I'd be willing to donate my code to this project (and I think it would benefit everyone).
 
Thanks
GeneralRe: Frames Security, and Normailzationmemberywusa200126 Aug '07 - 3:50 
Could you post a website where you got this problem?
 
Thanks.
GeneralUnspecified exception thrown when trying to find IEmemberblottie4 Apr '07 - 10:38 
Hi,
 
First of all a huge thank you for the code, it has been a fantastic help.
But I have sometimes have the same problem as the one mentioned by yousefk, if i rollout the programm on another machine. On some machines it is OK, but on other machines the following error is thrown whenn a new instance of IEDriver is created:
 
System.Runtime.InteropServices.COMException (0x80004005): Unspecified error
at SHDocVw.IWebBrowser2.get_HWND()
at IEAutomation.IEDriver..ctor()
 
I install the progamm using a asp.net setup programm, and it copies the files IEDriver.dll, Interop.SHDocVw.dll and Microsoft.mshtml.dll with my .exe. The other machine has exactly the same OS (win xp 2002 sp 2) and Internet Explorer (6.0.2900 SP 2) as my developer machine and the other PC where it does run correctly.
 
Anybody has any idea what the problem might be? Any hints would be greatly appreciated.
 
Thanks
GeneralRe: Unspecified exception thrown when trying to find IEmemberblottie4 Apr '07 - 12:13 
After reading the other comments, i found the solution in texios post somewhere down.
 
Changing the constructor did the job, I paste his comment down here:
 
When I tried to create an instance of IEDriver an unknown Exception was thrown. I corrected the problem by changing the constructor from:
 
public IEDriver() {
Process m_Proc = Process.Start("IExplore.exe");
Thread.Sleep(500);
_IE = null;
ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();
foreach(InternetExplorer Browser in m_IEFoundBrowsers) {
if(Browser.HWND == (int)m_Proc.MainWindowHandle) {
_IE = Browser;
break;
}
}
IE.Visible = true;
IE.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(IE_DocumentComplete);
}
 
into:
 
public IEDriver() {
_IE = new InternetExplorerClass();
IE.Visible = true;
IE.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(IE_DocumentComplete);
}
 
Works the same way and is much easier I think. Anyway thank you for spending a lot of time on this IE Driver. This is very very useful piece of code.
GeneralRe: Unspecified exception thrown when trying to find IEmemberbenjiwa26 Apr '07 - 2:45 
Blottie, you rock my socks. Nice fix. I had the same problem on Vista.
GeneralRe: Unspecified exception thrown when trying to find IEmemberpopicul198028 Apr '09 - 22:41 
Maybe this is to late to answer your question Smile | :)


Check internet explorer, internet options, security tab, uncheck enable protected mode (IE7)


In the case of IE6 another security option might be the cause of the problem.


GeneralException thorowsmemberyousefk27 Mar '07 - 0:27 
Browser.HWND throw the following exception why ?:
{"Unspecified error" }
 
inside:
public IEDriver() {
if(Browser.HWND == (int)m_Proc.MainWindowHandle) {
_IE = Browser;
break;
}

 
what's wrong ?
 
Markos
GeneralRe: Exception thorowsmemberblottie4 Apr '07 - 12:14 
See my post one thread up, it has a solution. Seems to be the same problem.
GeneralAutomation of complex DHTML/AJAX applicationsmemberAlex Furman23 Mar '07 - 7:54 
You can also try SWExplorerAutomation (SWEA) from Webius http://webiussoft.com[^]. SWEA automates Web Browser.The program creates an automation API for any Web application developed with HTML, DHTML or AJAX. The Web application becomes programmatically accessible from any .NET language.
SWEA API provides access to Web application controls and content. The API is generated using SWEA Visual Designer. SWEA Visual Designer helps create programmable objects from Web page content.

 
AlexF

AnswerRe: Automation of complex DHTML/AJAX applicationsmemberZaunCPP28 Oct '08 - 11:00 
You can also try iMacros, this is what we are using for quite some time now.
 
Unlike IEDriver and SWExplorerAutomation, it can also automate and test Flash, Flex, Java and Silverlight applets. And it works with Firefox, too.
 
http://www.iopus.com/imacros/component.htm[^]
 
Hope this helps,
Michael
GeneralIE AutomationmemberGoku2619 Mar '07 - 3:52 
Hi,
 
I have a problem, i need login to my webpage throught windows services and a i can't access to property HtmlDocument.parentWindow. in windows forms applications this works.
 
This error appear me
 
System.RuntimeType.ForwardCallToInvokeMember
 
thanks
GeneralAdded useful functionality... hope this helps.memberTriLogic16 Mar '07 - 5:00 
I added static methods to the IEDriver class to capture and control an existing Internet Explorer instance. This can be used to control those pesky popup windows. Here is the code - enjoy!
 
        public static IEDriver FromWindow(string title, int delay, int count)
        {
            WindowList wl = new WindowList();
            WindowInfo wi = null;
 
            count = count > 0 ? count : 1;
            for (int j = 0; j < count && wi == null; j++)
            {
                wl.RefreshDesktopWindows();
                for (int i = 0; i < wl.Count; i++)
                {
                    if (wl[i].title.ToLower().Contains(title.ToLower()))
                    {
                        wi = wl[i];
                        break;
                    }
                }
                if (delay>0)
                    Thread.Sleep(delay);
            }
 
            if (wi == null)
                return null;
 
            IEDriver result = new IEDriver(wi.processID);
            result.Open();
            return result;
        }
And the window list class...
    public class WindowInfo
    {
        public IntPtr hWnd = IntPtr.Zero;
        public IntPtr lParam = IntPtr.Zero;
        public string title=null;
        public uint   processID=0;
    }
 
    public class WindowList : List<WindowInfo>
    {
        int _hWnd;
 
        public WindowList(int hWnd)
            : base()
        {
            _hWnd = hWnd;
        }
 
        public WindowList()
            : base()
        {
            _hWnd = 0;
        }
 
        public int hWnd
        {
            get { return _hWnd; }
            set { _hWnd = value; }
        }
 
        public int FindWindow(string windowName, bool wait)
        {
            IntPtr hWnd = WinAPI.FindWindow(null, windowName);
            IntPtr hZip = new IntPtr(0);
            while (wait && hWnd.Equals(hZip))
            {
                System.Threading.Thread.Sleep(500);
                hWnd = WinAPI.FindWindow(null, windowName);
            }
            return hWnd.ToInt32();
        }
 
        public int RefreshChildWindows()
        {
            this.Clear();
            WinAPI.EnumChildWindows(new IntPtr(_hWnd), ThisEnumWindows, new IntPtr(0));
            return this.Count;
        }
        
        public int RefreshWindows()
        {
            this.Clear();
            WinAPI.EnumWindows(ThisEnumWindows, new IntPtr(0));
            return this.Count;
        }
 
        public int RefreshDesktopWindows()
        {
            return RefreshDesktopWindows(0);
        }
        public int RefreshDesktopWindows(int desktop)
        {
            this.Clear();
            WinAPI.EnumDesktopWindows(new IntPtr(desktop), ThisEnumWindows, new IntPtr(0));
            return this.Count;
        }
 
        private bool ThisEnumWindows(IntPtr hWnd, IntPtr lParam)
        {
            int len = WinAPI.GetWindowTextLength(hWnd);
            StringBuilder sb = new StringBuilder(len+1);
            WindowInfo ci = new WindowInfo();
            ci.hWnd = hWnd;
            ci.lParam = lParam;
 
            WinAPI.GetWindowText(hWnd, sb, sb.Capacity);
 
            ci.title = sb.ToString();
            if (ci.title.Length > 1)
            {
                if (ci.title.Contains("Microsoft Internet Explorer"))
                {
                    WinAPI.GetWindowThreadProcessId(hWnd, out ci.processID);
                    this.Add(ci);
                }
            }
            return true;
        }
    }
And lastly the WinAPI class
    public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
 
    public class WinAPI
    {
        #region Wind32API
 
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
 
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
 
        // For Windows Mobile, replace user32.dll with coredll.dll
        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
 
        [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
        public static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount);
 
        [DllImport("user32.dll")]
        public static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint lpdwProcessId);
 
        [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
        public static extern int GetWindowTextLength(IntPtr hWnd);
 
        [DllImport("user32.dll")]
        public static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumWindowsProc lpEnumFunc, IntPtr lParam);
 
        #endregion
    }

 
You know neither the day nor the hour.

GeneralRe: Added useful functionality... hope this helps.memberTriLogic16 Mar '07 - 5:07 
Sorry,
 
I forgot to include the overloaded constructor I added that uses a process id - here is the code for that. One thing to remember though is that you'll need to add your own logic to not ALWAYS terminate and close the window - there are some cases (as in popups) where you do not want to do this in the class destructor. I also added a boolean property named TerminateOnDestroy that governs this behavior. Easy enough to implement on your own.
 
Overloaded Constructor
 
   public IEDriver(uint processID)
   {
      mProcess = Process.GetProcessById((int)processID);
   }

 
You know neither the day nor the hour.

GeneralRe: Added useful functionality... hope this helps.memberNinjaCross28 Jun '07 - 3:55 
Thankyou so much for sharing Smile | :)
Just for the sake of accuracy, I'm listing here below some missing parts in your code:
- FromWindow -> looking at one of the last rows there is the "result.Open();" call, but the Open method doesn't exists
- In your added constructor the mProcess variable is undefined
 
--
NinjaCross
www.ninjacross.com

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 25 Feb 2005
Article Copyright 2005 by Leslie Hanks
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid