Sunteți pe pagina 1din 13

A Web Browser in C#

This article describes creating a web browser completely in C#. The application hosts a
Microsoft WebBrowser Control and uses the functions it provides for all control. Here is a
screenshot:

A lot of the functions do not work yet; most require some non-.NET programming to work. I
stuck to pure .NET programming for this app, because it is meant to demonstrate features of
the .NET Framework and not some APIs.
Building the Web Browser
Before you begin, you must generate some assemblies from the WebBrowser typlibs, so that they
can be used in our code. Typlibs must be imported for:
• The WebBrowser control itself, which is in SHDocVw.dll.
• mshtml.tlb, if you plan to access the DHTML Object Model of the document.
This step is easy. At a command prompt, in a folder you create for this project, type:

Collapse
aximp c:\windows\system\shdocvw.dll
tlbimp mshtml.tlb
The aximp command should generate two files: AxSHDocVw.dll and SHDocVw.dll. The tlbimp
command should generate MSHTML.dll, which contains definitions for the DHTML DOM
interfaces, along with about 3000 other types, so it might take a while to import.
Now you can proceed in several ways: You can do all coding by hand, or you can use Visual
Studio.NET. I have done it the 'SDK way'. Basically, you have to create a form with:
• The WebBrowser control itself.
• A toolbar. Note that not all buttons on the toolbar work as you might expect them to.
• A status bar. You can add panels for the status message, a progress bar, offline and secure
icons, and a zone indicator. I've added these controls as placeholders only, they don't
work (yet).
• An address bar. This should be a panel with a label, a combo box, and a Go button.
• A main menu for the application.
• An image list for the toolbar.
Most of the initialisation code shall be added for you and little work needs to be done here. You
must remember to add event handlers for the WebBrowser control, the status bar, the menus, the
toolbar, the address combo box, and the Go button. All this code is present in the file
WebBrowser.cs. In addition, extra dialogs are included in About.cs, ImportExport.cs, and
Open.cs.
In the WebBrowser.cs file, you must put in the following statements in the namespace:

Collapse
namespace ND.WebBrowser
{

using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using Microsoft.Win32;
using AxSHDocVw;
using MSHTML;

// etc..

Microsoft.Win32 is required because the application loads the URL MRU list from the registry.
you can remove the MSHTML reference if you do not need it.
Notice SHDocVw is not included; this causes conflicts with the definitions in AxSHDocVw.dll.
Most of the code is simple and calls functions of the WB control.
Menus and Toolbars
The menu and the toolbar are standard Windows Forms stuff. Menu popup events are handled to
update the enabled/disabled and checked state of menu items. For example:

Collapse
protected void mnuFile_Popup(object sender, EventArgs e)
{
MenuItem miFile = MenuMain.MenuItems[0];
miFile.MenuItems[14].Checked = AxWebBrowser.Offline;

Int32 EnabledTest = Convert.ToInt32(SHDocVw.OLECMDF.OLECMDF_SUPPORTED)


+ Convert.ToInt32(SHDocVw.OLECMDF.OLECMDF_ENABLED);

miFile.MenuItems[2].Enabled =
EnabledTest.Equals(AxWebBrowser.QueryStatusWB //Refresh test for Edit

(SHDocVw.OLECMDID.OLECMDID_REFRESH));
miFile.MenuItems[3].Enabled =
EnabledTest.Equals(AxWebBrowser.QueryStatusWB
(SHDocVw.OLECMDID.OLECMDID_SAVE));
miFile.MenuItems[4].Enabled =
EnabledTest.Equals(AxWebBrowser.QueryStatusWB
(SHDocVw.OLECMDID.OLECMDID_SAVEAS));
miFile.MenuItems[6].Enabled =
EnabledTest.Equals(AxWebBrowser.QueryStatusWB
(SHDocVw.OLECMDID.OLECMDID_PAGESETUP));
miFile.MenuItems[7].Enabled =
EnabledTest.Equals(AxWebBrowser.QueryStatusWB
(SHDocVw.OLECMDID.OLECMDID_PRINT));
miFile.MenuItems[8].Enabled =
EnabledTest.Equals(AxWebBrowser.QueryStatusWB
(SHDocVw.OLECMDID.OLECMDID_PRINTPREVIEW));
miFile.MenuItems[13].Enabled =
EnabledTest.Equals(AxWebBrowser.QueryStatusWB
(SHDocVw.OLECMDID.OLECMDID_PROPERTIES));
}
First, the File menu object is obtained. Then the WB control is used to check the enabled status
of commands in the menu. If you are familiar with COM programming, this should be standard
code. Otherwise, read the WebBrowser control documentation at MSDN: WebBrowser. Most
commands are also executed in the standard COM IOleCommandTarget way, like this:

Collapse
protected void mnuFileSave_Click(object sender, EventArgs e)
{
Object o = null;
m_axWebBrowser.ExecWB(SHDocVw.OLECMDID.OLECMDID_SAVE,
SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT,
ref o, ref o);
}
A null object reference is passed for the input and output arguments of the ExecWB method.
Simply because we have no arguments to pass. Some menu commands use methods of the
WebBrowser control itself, like Home and Search. The other source files have other dialogs, like
the Import & Export dialog.

Collapse
protected void mnuFileOpen_Click(object sender, EventArgs e)
{
OpenForm frmOpen = new OpenForm();
frmOpen.ShowDialog(this);
if(frmOpen.DialogResult == DialogResult.OK)
{
Object o = null;
AxWebBrowser.Navigate(frmOpen.Address, ref o, ref o, ref o, ref o);
}
}
The Import and Export dialog uses the ShellUIHelper object, documented at MSDN: Shell
Helper API.
Editing the Document
Instead of calling an external editor, all editing is done by the WebBrowser control itself, using
an IE 4 feature which allows documents to make themselves editable. However, our code only
invokes the edit mode, and does nothing beyond that.

Collapse
protected void mnuFileEdit_Click(object sender, EventArgs e)
{
IHTMLDocument2 doc;
object boxDoc = AxWebBrowser.Document;
doc = (IHTMLDocument2)boxDoc;
doc.designMode = "On";
}
The code first gets a reference to the Document object and then unboxes it to get to the
IHTMLDocument2 interface. This is necessary because the WebBrowser control returns the
document as an object and not an IHTMLDocument2 pointer.

The Finished Code


That just about sums up most of the code. However, a lot of things do not work yet. Here is a
short list:
1. 'Full Screen' and 'View Source' in the application menus.
2. Enumeration of the user's Favourites and History.
3. 'Send' submenu of 'File' menu.
4. Mail button on toolbar.
5. Edit works to only to a limited extent.
6. Tools Menu.
7. Back and Forward drop-downs.
8. Some pages, especially those with frames, do not load properly. ( ? )
9. There is no handling for new windows.
10. Status bar icons (secure, offline, zone) are not displayed.
Most code should be easy to create, and can be done within the .NET Framework. However,
some functions, like those for favourites and history, shall involve PInvoke.
Top of Form
/w EPDw UKMTAy

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
Nikhil Dabas
Occupation: Chief Technology Officer
Company: TechnoApex Software
Location: India

Member

Other popular C# articles:


• Asynchronous Method Invocation
How to use .NET to call methods in a non-blocking mode.
• IconLib - Icons Unfolded (MultiIcon and Windows Vista supported)
Library to manipulate icons and icons libraries with support to create, load, save, import
and export icons in ico, icl, dll, exe, cpl and src format. (Windows Vista icons supported).
• I/O Ports Uncensored - 1 - Controlling LEDs (Light Emiting Diodes) with Parallel Port
Controlling LEDs (Light Emiting Diodes) with Parallel Port
• 100% Reflective Class Diagram Creation Tool
100% Reflective Class Diagram Creation Tool
• Processing Global Mouse and Keyboard Hooks in C#
This class allows you to tap keyboard and mouse and/or to detect their activity even when
an application runs in the background or does not have any user interface at all.

Java Source Code Browser


The Java Source Code Browser reads a designated set of Java source files and produces a
JavaDoc equivalent extended with fully browsable source code containing hyperlinked cross-
references within and across that set of files. Every identifier in the source code (public or local)
acts as a link to its corresponding source definition, all uses of that identifier anywhere in the
source files, and the corresponding JavaDoc information. This provides a convenient method for
programmers to view the entire source of large application systems; this can help cut down the
50% of the time that programmers typically spend just looking at source code. It is also ideal for
on line reference and code reviews.
Java Browser Features
• JavaDoc tag compatible
• Java 1.1,1.2,1.3 and 1.4 compatible
• Produces JavaDoc equivalent web pages
• Extracts full cross-reference and type information from both source and class
files
○ JavaDoc page for each identifier links to actual source code and all
uses according to language rules.
○ Source files are prettyprinted with clickable identifier links to definition
source and corresponding JavaDoc page.
• Can handle extremely large systems of source code
• Optional specification of files via graphical project file chooser
Sun's JavaDoc has a -linksource option that provides a much weaker cross reference. Unlike the
Source Browser, it only provides links from JavaDoc pages to source text, but no source-to-
documentation links, and no full-cross reference of definitions and uses.
You can see a sample of the Browser results applied to the popular JUnit program. To get a full
value from this sample, in the Packages window, click on any Junit package, click on any class
and then browse its source, clicking on identifiers: Browsable JUnit Sources.
Generating a set of pages like this nightly and placing it on your intranet would make current
sources easily available to developers and support engineers. You can also download a ZIP file
(5Mb) containing the HTML pages for this example to try out this idea.
The Source Code Browser is a derivative of SD's family of Source Code Formatters.
Autoextraction of JavaDoc-like tags can also be implemented (e.g., automatically generate
function signature and parameter tags if not already present). Similar browsers can be
constructed for other languages. Inquire for custom features.

This is a simple and specific tutorial on how to make a basic web browser in Visual
Basic 6.

Steps 1-3
Create a new project, and then go to "Project" on the menu.
Click components as shown in the following image.

Find the component "Microsoft Internet Controls," check it, and click "Apply" and
then "Close."
Click the icon that was just added in the tools window, and draw a large sized
window with it. This is going to be where you view webpages through your browser,
so don't make it small, but leave room for buttons and other accessories.

Steps 4-6
Make a textbox, this will be your URL bar where you type in the address of the
website you want to see.

Make four command buttons, these are going to be your Go, Back, Forward, and
Refresh buttons, change the captions accordingly, and name each of them Cmdgo,
Cmdback, CmdForward, and CmdRefresh.

Now, here's the coding part. This is all it takes to make your webbrowser working.

CODE

Private Sub cmdback_Click()


WebBrowser1.GoBack
End Sub

Makes the back button go backwards, pretty much self explanatory.

CODE

Private Sub Cmdforward_Click()


WebBrowser1.GoForward
End Sub

Same concept, except this time the webbrowser goes forward.

CODE

Private Sub cmdgo_Click()


WebBrowser1.Navigate (Text1.Text)
End Sub

Makes your webbrowser go to the URL in your text box.

CODE

Private Sub cmdrefresh_Click()


WebBrowser1.Refresh
End Sub

Makes your web browser refresh.

CODE

Private Sub Form_Load()


WebBrowser1.Navigate ("http://thyelite.com")
End Sub

The URL shows your homepage, change it to http://google.com or whatever your


usual homepage you would like to be.

CODE

Private Sub WebBrowser1_StatusTextChange(ByVal Text As String)


Text1.Text = (WebBrowser1.LocationURL)
Form1.Caption = (WebBrowser1.LocationName)
End Sub

This changes the text box's text into what URL that you're
currently at, and the next line makes the Snippet
1. import java.awt.*;
2. import java.awt.event.*;
3. import java.util.*;
4. import java.net.*;
5. import java.io.*;
6. import javax.swing.*;
7. import javax.swing.event.*;
8.
9. public class WebBrowser
10.{
11. public static void main(String [] args)
12. {
13. JFrame frame = new EditorPaneFrame();
14. frame.show();
15. }
16.}
17. class EditorPaneFrame extends JFrame
18.{
19.
20. private JTextField url;
21. private JCheckBox editable;
22. private JButton loadButton;
23. private JButton backButton;
24. private JEditorPane editorPane;
25. private Stack urlStack = new Stack();
26.
27.
28. public EditorPaneFrame()
29. {
30. setTitle("Java Web Browser");
31. setSize(600,400);
32. addWindowListener(new WindowAdapter()
33. {
34. public void windowClosing(WindowEvent e)
35. {
36. System.exit(0);
37. }
38. } );
39.
40. // set up text field and load button for typing
in URL
41.
42. url = new JTextField(30);
43.
44. loadButton = new JButton("Load");
45. loadButton.addActionListener(new ActionListener()
46. {
47. public void actionPerformed(ActionEvent
event)
48. {
49. try
50. {
51. // remember URL for back button
52. urlStack.push(url.getText());
53. editorPane.setPage(url.getText());
54. }
55. catch(Exception e)
56. {
57. editorPane.setText("Error: " +e);
58. }
59. }
60. });
61.
62. // set up back button and button action
63.
64. backButton = new JButton("Back");
65. backButton.addActionListener(new ActionListener()
66. {
67. public void actionPerformed(ActionEvent
event)
68. {
69. if(urlStack.size()<=1) return;
70. try
71. {
72. urlStack.pop();
73. String urlString =
(String)urlStack.peek();
74. url.setText(urlString);
75. editorPane.setPage(urlString);
76. }
77. catch(IOException e)
78. {
79. editorPane.setText("Error : " +e);
80. }
81. }
82. });
83.
84. editorPane = new JEditorPane();
85. editorPane.setEditable(false);
86. editorPane.addHyperlinkListener(new
HyperlinkListener()
87. {
88. public void hyperlinkUpdate(HyperlinkEvent
event)
89. {
90. if(event.getEventType() ==
HyperlinkEvent.EventType.ACTIVATED)
91. {
92. try
93. {
94.
urlStack.push(event.getURL().toString());
95.
url.setText(event.getURL().toString());
96.
97.
editorPane.setPage(event.getURL());
98. }
99. catch(IOException e)
100. {
101. editorPane.setText("Error: "
+ e);
102. }
103. }
104. }
105. });
106.
107. editable = new JCheckBox();
108. editable.addActionListener(new ActionListener()
109. {
110. public void actionPerformed(ActionEvent
event)
111. {
112.
editorPane.setEditable(editable.isSelected());
113. }
114. });
115.
116. Container contentPane = getContentPane();
117. contentPane.add(new JScrollPane(editorPane),
"Center");
118.
119. JPanel panel = new JPanel();
120. panel.add(new JLabel("URL"));
121. panel.add(url);
122. panel.add(loadButton);
123. panel.add(backButton);
124. panel.add(new JLabel("Editable"));
125. panel.add(editable);
126.
127. contentPane.add(panel,"South");
128. }
129.
130.}
131.

Copy & Paste


panel.add(loadButton);
panel.add(backButton);
panel.add(new JLabel("Editable"));
panel.add(editable);

contentPane.add(panel,"South");
}

caption of your form into the header of the URL.Bottom of Form

S-ar putea să vă placă și