显示标签为“编程人生”的博文。显示所有博文
显示标签为“编程人生”的博文。显示所有博文

2009-03-31

Comparing iFrame and FBML Flash Facebook applications

The following table
summarizes the differences when creating your Flash Platform application as an
iFrame or FBML Facebook application. The two most significant differences are
the ability to control the embedding of a Flash object and the ability to
access scripts.















































Feature

iFrame

FBML

Flash Player version and detection code

You control the embedding. You write (or include) the
JavaScript detection code and the selection of the required Flash Player
version. Typically, SWFObject is used.

You have no control over the embedding. Currently, the <FB:swf> tag requires Flash Player version 9.0.115 and there is no way to specify any
other version.

Script access

Can be denied by setting allow_script_access=never.

This means no full screen, no JavaScript, etc.

Use fb:fbjs-bridge for limited JavaScript access on FBML pages.

Fullscreen mode

Supported.

Not supported.

Simple integration of FBML tags

Supported through use of XFBML.

Supported. This allows you to simply integrate
Facebook components and dialog boxes. You can also embed Flash objects in the fb:iframe tag.

Application server

Not required. Your SWF container page could just be an
HTML page that uses JavaScript to parse and pass the GET URL session
variables passed with the page request to the SWF by setting the flashvars property of the SWFObject.

Not required. Your SWF can be a static HTML or FBML
page.

Making Facebook API calls from Flash

Supported.

Supported.

Controlling URL history

Supported through iFrame URL.

Supported by browser.


References



Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License




About the author



This content was authored by Facebook.


Getting your head around Flash on Facebook


Getting your head around Flash on Facebook







Recently I had the opportunity to take an Adobe AIR
application, nomee.com, and integrate a portion of it into Facebook. In this
article I'm going to cover some of the things that I learned along the way
while I was trying to understand exactly what I could and couldn't do inside of
Facebook.


The Nomee application


Figure 1. The Nomee application


First I'll start with an overview of the different places
you can put Flash applications on the Facebook site, followed by an overview of the
different ways to launch Flash applications in the Facebook Platform. Then I will talk about flashvars in the world of Facebook. I'll end with a quick overview of what you can't do
with Flash on Facebook.


Where you can run Flash


Facebook has a number of integration points throughout the
site. These are covered in more detail in the Facebook
developer wiki
page. The main points of integration are the Canvas page,
Application tab, Boxes tab, and Wall.


Important:
Except on your canvas page, Facebook restricts how Flash applications
can run. Before any Flash application can run on the Application or
Boxes tabs or Wall, the user has to click the placeholder to activate
the Flash movie. This is a lot like how YouTube places the big play
button on top of YouTube videos. Facebook does this so that developers
don't fill up Facebook pages with lots of animated, noise-making
applications running at the same time on a page. Because Flash can do
so much, users need to start the applications.


Luckily, Facebook gives you the ability to create your own
placeholder graphic that can tell users to click the graphic to start the
Flash movie. This is set with the <fb:swf imgsrc=""> attribute.


Canvas page


Every application is given a unique application URL by
Facebook when you register your application in the Developer section. This URL
starts with http://apps.facebook.com/ and is followed by a unique name of your choosing. Facebook will proxy requests
to this domain to your real web server so users will never need to know the URL
to your server. It also allows you to change your servers as needed without
breaking Facebook bookmarks.


For example, if you are requesting:


http://apps.facebook.com/<em>yourappname</em>/usersInfo.htm</pre>
<p>Facebook (behind the scenes) will request <kbd>userInfo.htm</kbd> from your server and return it to the user on Facebook. By doing it this way,
you are able to run Facebook Markup Language (FBML) on your pages even if the
application is hosted in an iFrame. </p>
<p>The main application page has the least amount of
restrictions on it. You can use URL parameters, you can run your own ads, and Facebook
doesn't sanitize the JavaScript you want to run. </p>
<p>You are given two choices when setting up your Facebook
application. You can run it as straight FBML or as an iFrame inside of the
Facebook page. When you run it as FBML you will get to see some benefits
from Facebook caching of the FBML page; however, you will also be slightly
limited on what you can do. Specifically, you won't be able to pass URL
parameters into your pages. </p>
<p>With the nomee application, our plan was to redirect a large
portion of the traffic back to our application page for two reasons: we have the
ability to run ads and, more importantly, we needed a guaranteed way to view a
user's nomee card. When users embed their cards on Facebook, from our AIR
client, we have no guarantees that they may actually add our application to
their profile pages. However they will now show up in searches and friends of
theirs may want to view their cards. By redirecting all of these views back to
the canvas page we can always show the card to their friends. </p>
<h4>Application tab</h4>
<p>Once users have authorized your application, they have the
ability to create a tab in their profile for your application. These are the
tabs you see when you visit your friends' profile pages. You can remind
users to add this tab. However, it's up to the user to create this tab in the
settings panel for your application or with the + sign next to the existing
tabs in his or her profile.</p>
<p class="note"><strong>Note:</strong> They have to do that in the
Facebook settings panel for your application. You cannot force the creation of
that tab through the API or FBML code. </p>
<p>When a user adds a tab for your application you need to
define a special page on your server for this tab. The code on this page needs
to be a straight FBML page served up to Facebook. However, you can still run
the request through a middleware server (such as ColdFusion, JSP, or ASP). </p>
<p>This tab page will be running as a section of the larger
Facebook page so you don't have to add the regular wrapper HTML to this page; I'm
referring to the <code><HTML><HEAD><BODY></code> tags. This is why it
needs to be a different page; however, since all of your logic may be in the
SWF file this could be as simple as a <code><fb:swf></code> tag. </p>
<h4>Boxes tab and Wall</h4>
<p>Another place that you can run your Flash movie, is on the
predefined Boxes tab for the user. The page on this tab has two columns, one
wide and one narrow. The user also has the option of taking any item on the Boxes
tab and moving into the left side column of their Wall page, too.</p>
<p>Again, users control where they want the box for your
application positioned in relationship to all of the other application boxes on
this page or their Wall pages.</p>
<p>The code for the Boxes tab and the Wall page work
differently than the Profile tab. For these pages you need to post the FBML to
Facebook beforehand. You do this with the <code>setFBML()</code> method of the
Facebook API:</p>
<pre>var profileWall = "<span class="asDoc"><a</span> <span class="asDoc">href=</span>''<span class="asDoc">><img</span /> <span class="asDoc">src=</span>'' <span class="asDoc">width=</span>'184' <span class="asDoc">height=</span>'250' <span class="asDoc">border=</span>'0'<span class="asDoc">></a></span><span class="mxmlTag">";</span><br /> <br />var profileBox = "<span class="asDoc"><a</span> <span class="asDoc">href=</span>''<span class="asDoc">><img</span /> <span class="asDoc">src=</span>'' <span class="asDoc">width=</span>'700' <span class="asDoc">height=</span>'250' <span class="asDoc">border=</span>'0'<span class="asDoc">></a></span><span class="mxmlTag">";</span><br /> <br />api.profile_setFBML(api.get_session().uid,<br />profileWide, null, null, profileNarrow, <br /> function(){}<br />);</pre>
<p>Facebook will then cache the FBML page and serve the content
directly to the user. This moves the server traffic load directly onto the
Facebook servers. However, it also means the data is cached on Facebook and you
need to reset the code with <code>setFBML</code> before Facebook knows about new code. </p>
<h3>Running Flash applications inside an FBML page</h3>
<p>When you are running Flash applications inside of an FBML page, either in
an Application tab or your Canvas page, you will launch your Flash application
with the <code><fb:swf></code> tag. This is the FBML tag that Facebook uses to control how and when the Flash
application starts as well as what parameters are passed to the Flash application. </p>
<p>You do have two options of how to invoke this tag. You can
do it directly with FBML markup, as shown in this snippet: </p>
<pre><fb:swf swfbgcolor="000000" <br /> imgstyle='color:white;"<br /> swfsrc='<URL TO YOUR SWF>'<br /> imgsrc='<URL TO PLACEHOLDER GRAPHIC>s' <br /> width='340' height='270' /></pre>
<p>Or you can do it in script with the <code>createElement("fb:swf")</code> tag:</p>
<pre><div id="swfContainer"></div> <br /><script> <br /> var swf = document.createElement('fb:swf'); <br /> swf.setId('my_swf_id'); <br /> swf.setWidth('100'); <br /> swf.setHeight('100'); <br /> swf.setSWFSrc('FULL_URL_TO_MY_SWF');<br /> document.getElementById('swfContainer').appendChild(swf);<br /></script> </pre>
<p>By doing it in script you have the option of dynamically
setting up the URL to the SWF file, place holder image, or any other parameters of
the Flash application. FBML itself doesn't have the ability to set properties
dynamically like you would in Flex with the {Binding} syntax. </p>
<p>Another thing to consider with FBML pages, including the
FBML for the Boxes tab and Wall, is that Facebook will parse your code before
serving it up and rewrite or (as I like to call it) sanitize the code.
Specifically, the JavaScript on the page is parsed for unauthorized code and
Facebook will also rename functions and variables as needed too. There are a
number of JavaScript functions that you are not allowed to run in an FBML page.
Facebook will strip these items out to protect their users from potentially
harmful application code. An indispensible tool when debugging Facebook
applications is the Firefox plug-in, <a href="http://getfirebug.com/" target="_blank">Firebug</a>. </p>
<h4>Running Flash applications inside a canvas page (iFrame)</h4>
<p>The canvas page is nice and I would recommend it because it
gives you full control of how your application runs. Because this page is
running in an iFrame, you can run any html or JavaScript that you need. </p>
<p>I've also found that URL parameters passed to the canvas
page are passed through to the iFrame; however, I was never able to find a way
to get access to these URL parameters in an FBML page, so this is another
benefit to using an iFrame page if you can. </p>
<p>To invoke Flash in an iFrame page you have a couple of
choices: You have the Facebook <code><fb:swf></code> tag and <code>createElement("fb:swf")</code> option, just like in the FBML page. You can also use the basic <code><div class="youtube-video"><object><embed></code> tags or a third-party JavaScript library like <a href="http://code.google.com/p/swfobject/" target="_blank">SWFObject</a>. One thing to note if
you don't use <code><fb:swf></code> to invoke the Flash application, then you will
need to pass in the Facebook URL parameters as <code>flashVars</code> youself (if
you need them). </p>
<p>Here is a simple sample that uses SWFObject and pulls out
any URL parameters and then passes them into the Flash movie as <code>flashVars</code>:</p>
<pre><script src=<span class="asReserved">"http://static.ak.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"</span> type=<span class="asReserved">"text/javascript"</span>></script><br /><script type=<span class="asReserved">"text/javascript"</span>><br /> <br /> <span class="asReserved">var</span> api_key <span class="asReserved">=</span> <span class="mxmlTag"><your api key></span>;<br /> // the xd_reciever.htm file needs to be on your website <br /> // relative to your facebook application pages.<br /> // For more information: <br /> // http://wiki.developers.facebook.com/index.php/Cross-domain_communication_channel<br /> <span class="asReserved">var</span> channel_path <span class="asReserved">=</span> <span class="mxmlTag">'xd_receiver.htm'</span>;<br /> <br /> FB_RequireFeatures([<span class="mxmlTag">"XFBML"</span>], <span class="asReserved">function</span>(){<br /> FB<span class="asReserved">.</span>Facebook<span class="asReserved">.</span>init(api_key, channel_path);<br /> });<br /> <br /> <br /> <span class="asReserved">var</span> queryString <span class="asReserved">=</span> window<span class="asReserved">.</span>location<span class="asReserved">.</span>search;<br /> <span class="asReserved">var</span> flashVars <span class="asReserved">=</span> {};<br /> queryString <span class="asReserved">=</span> queryString<span class="asReserved">.</span>substring(<span class="mxmlString">1</span>);<br /> <br /> <span class="asReserved">var</span> fields <span class="asReserved">=</span> queryString<span class="asReserved">.</span>split(<span class="mxmlTag">'&'</span>);<br /><span class="asReserved"> var</span> fb_sig_added <span class="asReserved">=</span> <span class="mxmlString">0</span>;<br /> <br /><span class="asReserved"> for</span> (<span class="asReserved">var</span> i <span class="asReserved">=</span> <span class="mxmlString">0</span>; i <span class="asReserved"><</span> fields<span class="asReserved">.</span>length; i<span class="asReserved">++</span>) {<br /> <span class="asReserved">var</span> index <span class="asReserved">=</span> fields[i]<span class="asReserved">.</span>indexOf(<span class="mxmlTag">'='</span>);<br /> <span class="asReserved">var</span> key <span class="asReserved">=</span> fields[i]<span class="asReserved">.</span>substring(<span class="mxmlString">0</span>, index);<br /> <span class="asReserved">var</span> value <span class="asReserved">=</span> fields[i]<span class="asReserved">.</span>substring(index <span class="asReserved">+</span> <span class="mxmlString">1</span>);<br /> <br /> <span class="asReserved">if</span> (key<span class="asReserved">.</span>toLowerCase() <span class="asReserved">==</span> <span class="mxmlTag">"fb_sig_added"</span>){<br /> fb_sig_added <span class="asReserved">=</span> value;<br /> }<br /> <br /> flashVars[key] <span class="asReserved">=</span> value;<br /> }<br /> <br /> // first check if they have authorized the app, if not<br /> // redirect them to the login page.<br /> <span class="asReserved">if</span> (fb_sig_added <span class="asReserved">==</span> <span class="mxmlString">0</span>)<br /> {<br /> window<span class="asReserved">.</span>parent<span class="asReserved">.</span>location <span class="asReserved">=</span> <span class="mxmlTag">"http://www.facebook.com/login.php?api_key="</span> <span class="asReserved">+</span> api_key <span class="asReserved">+</span> <span class="mxmlTag">"&next=index.htm&v=1.0&canvas=1"</span>;<br /> <br /> }<br /> else<br /> {<br /> // load the flash movie.<br /> swfobject.embedSWF(<span class="mxmlTag">"http://<your domain>/facebook/FacebookClient.swf"</span>, <span class="mxmlTag">"flashContent"</span>,<br /><span class="mxmlTag"> "700"</span>, <span class="mxmlTag">"650"</span>, <span class="mxmlTag">"10.0.0"</span>, <span class="mxmlTag">"expressInstall.swf"</span>, flashVars, null, null);<br /> }<br /> <br /><span class="asDoc"></script></span>

A note on flashVars and the Facebook Platform


When Facebook runs an FBML or iFrame application, a
number of parameters are available to you. If you are using the <fb:swf> tag,
parameters will be passed in as flashVars automatically.


Note: For a complete list of parameters, refer to the Facebook
Developers wiki
.


Pay close attention to the fb_sig_user, fb_sig_canvas_user,
, fb_sig_profile, fb_sig_profile_user parameters. Depending on the context of when and where your Flash application
is invoked or if the user hasn't authorized your application yet, any one of these
variables could be the Facebook uid of the user using your application.


What you can't do in Flash


The Facebook Platform API lets you do a lot, and most of
those things are easily doable inside of a Flash application; however, there
are still a few things that are FBML only and to the best of my knowledge there
is no way to do them through the API from inside of an Flash application. For these you
will need to put them in the HTML around the Flash application. Or on another
application page altogether. Two of these that I ran into are:


  • <fb:add-to-profile>: This is the FBML tag that users
    need to use to take the FBML you set in Facebook for the Boxes tab and Wall and
    actually add that to their Facebook pages; otherwise, users will never see the
    FBML you set.
  • <fb:request-form>/ <fb:multi-friend-selector>:
    Facebook recently launched a new Friend Selector UI control. Your application
    uses this control to allow users to select friends usually to send application
    invitations to. You can build your own Friend selector in Flash but you won't
    be able to send out Facebook invitations; instead, you'll need to send out your
    invitations as Facebook notifications.

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License




About the author



Mike Nimer is the Director of Engineering and Architect of
the nomee.com application. Before joining
nomee, Mike has spent over a decade building web applications, the servers that
run web applications, as well as providing consulting and mentoring help for
development teams around the world. Mike was a founding partner of Digital
Primates IT Consulting Group, providing mentoring and development support on
the Adobe Flash Platform and ColdFusion. Prior to Digital Primates, Mike was a
member of the Adobe ColdFusion engineering team where he was responsible, in
part, for a number of key features, including PDF generation and the
integration of Flex 2 with ColdFusion Server.


Understanding the architecture of applications built on the Facebook and Flash Platforms

Understanding the architecture of applications built on the Facebook and Flash Platforms | Developer Center

Understanding the architecture of applications built on the Facebook and Flash Platforms

The Flash Platform lets you build rich, user experiences. The Facebook Platform lets you build rich, social experiences. Put the two together, and you can build killer applications incorporating social capabilities in highly interactive, expressive, and responsive applications.

This article introduces you to the architecture of applications using the Facebook and Flash Platforms. It provides an overview of the different types of applications you can build and how the applications communicate with your server and the Facebook server.
The types of applications you can build

You can build three types of Flash Platform applications to integrate with Facebook: applications on Facebook, external website applications, and desktop applications.

* Applications on Facebook are web applications that are hosted on your own server but which users access from the Facebook website. The user sees the Facebook chrome with your application inside of it. You visit an application on Facebook (often by either responding to a friend's invitation or by following a link when searching for an application) and the Facebook server proxies the request to your server and retrieves an application page (HTML and JavaScript) to display on the Facebook website. This provides a seamless experience to users when they are on the Facebook website; users never leave the Facebook website. Examples include the Who Has the Biggest Brain application from Playfish and Zynga's Texas Hold'em Poker.
* External website applications also are hosted on your own server, but users access them through your URL, not through the Facebook website. On external websites, you can use the Facebook API or Facebook Connect to add social features from Facebook. If you use the Facebook API to log in, users will be directed to the Facebook website in a new browser window where they must log in before returning to your application. To provide a seamless login experience without requiring logging on the Facebook website, you use Facebook Connect. For example, a user may be reading a blog and may want to enter a comment. Instead of requiring that the user create yet another account for another website, let her use her Facebook account to log in. In addition to streamlining the login process, your application can now also access all of the user's data; for example, the user's name and picture can be displayed next to her name when she posts a comment. Similarly, on a shopping website, by letting the user log in with her Facebook profile, you could then check to see if any of her friends have recommended products or submitted product reviews. Live examples include RedBull Connect and City Search which let you add comments or reviews on their websites, see any of your friends' comments or reviews, and also publish your comments or reviews to your Facebook Wall and your friends' News Feed if you want.
* Desktop applications are similar to external website applications except that you deploy your Flash Platform application as an AIR application to the desktop instead of hosting it on a website. AIR desktop applications also use the Facebook Connect to provide a seamless Facebook login for the user. Examples include Seesmic for Facebook and Nomee.

One of the first steps in creating a Facebook application is registering it with the Facebook Developer application so you can get an API key and secret key for that specific application. For details, step through the Building your first Facebook application quick start tutorial.

During the registration process, you specify settings for your application; you must set whether your application is a web or desktop application and whether your application will use FBML or an iFrame.

* For applications on Facebook, you select web application and then either an iFrame or FBML application.
* For external website applications, you specify Facebook Connect information.
* For desktop applications, you specify desktop application,

Let's take a look at the architecture of typical, embedded, non-Flash iFrame and FBML Facebook applications before delving into the architecture of embedded Flash Platform based applications, external Flash Platform websites, and Flash Platform desktop applications.

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License

2008-12-27

Moodle Makeover

Moodle Makeover:

Moodle Makeover

In this article by Ian Wild, we will change the look of our Moodle website. Specifically, we will use our resources within Moodle to make our topics more visually appealing. We would include an animated character. We will take a good look at different tips and tricks to make our courses more interesting for students.

What we will do, is:

* Do more than make each topic a long list of resources. Use the label resource and Moodle's indenting tool to change this:

To this:

* Find out where we can get lots of free images for our courses.
* Explore different ways to use HTML to make our courses even more engaging.
* Include a talking character—an animated avatar—using Voki.com:

Arrange Your Resources

Why is it important to spend a little time arranging resources in a topic? Isn't it all eye candy? Let's take a look at my Topic 1:

I've got a nice colorful title, some text to introduce the topic, and then a long list of resources—which, quite honestly looks just like the list of files in the shared drive I already use to distribute my documents and handouts to students. What if the topic looked like this:

This is much more the effect we need. I've reordered my resources and included some labels, so that it is much easier for students to find a resource. In this section, we're going to learn how to bring some order into our topics.
Putting Your Resources in Order

One obvious difference between a shared drive and Moodle is that in Moodle, you can put the resources in the order you want, not the order the computer insists on (usually, numerical/alphabetical). However, in Moodle, any new resources you add are simply queued on to the end of the topic. This has meant that resources in my Getting Things Flying topic aren't exactly ordered in a sensible way—just the way I added them. I'm going to take action to remedy that now...
Time for Action – Arrange Your Resources

1. Remember that you need editing turned on before you start.

2. Choose the resource you want to move. I'm going to move my Backyard ballistics links resource to the end of the topic. To start the process, I need to 'pick up' the resource. I click on the Move icon:
3. This causes two things to happen. Firstly, the resource I want to move disappears. Don't worry—imagine you have it in your hand and you are ready to place it back into your course. Secondly, the boxes that have now appeared represent all the places to which you can move the resource that you are holding:

4. Choose where you want to move the resource to. I want my list of links at the end, so I'm going to click on the box at the bottom. The boxes disappear and my resources have been shuffled:

What Just Happened?

A list o f resources in Moodle isn't simply a list of files, like you would find on a shared drive. One obvious difference is that in Moodle, you can arrange your resources to be listed in the order you want, and we've just seen how easy it is to achieve this.

You can't find the Move icon?
Your site may be configured so that you can drag and drop resources. In that case, instead of the Move icon you will see crosshairs next to your resource. To move the resource, click on the cross hairs and, keeping your finger pressed down on the left mouse butt on, drag the resource to its new location. Look for the line in the background—this tells you where your resource is going to be dropped to—then let go of the mouse butt on when you have found the spot.

Now I've got my resources in the order I wanted, I have to say that my topic looks like just another resource dump—which is what I am trying to avoid.

My resources would be much easier to use if I could introduce each of them with a short piece of text:

Introducing a resource with a short introduction is a great way of improving the visual appeal of your course. The tool to achieve this is called a Label resource, and here's how to use it...
Time for Action – Insert a Label

I'm going to start the process of arranging my resource by having a short piece of text introducing the Backyard ballistics links resource.

1. Make sure editing is turned on, click on Add a resource, and choose Insert a label.
2. In the Editing Label page, enter your label text. When you are done, press the Save and return to course button.
3. The new label is added to the end of the list of resources—which is obviously the wrong place for it. Click on the Move icon, next to the label you have just added:

4. The page is re-displayed. Your new label disappears and lots of boxes have appeared. These boxes represent the places where your new label can go:

5. Click on the relevant box to place your label. You're done!

Remember: If you don't have a Move icon, you'll have crosshairs next to the label that you can click on to drag it to the right place.


What Just Happened?

After all the experience we have had with Moodle so far, using the label resource will be fairly straightforward. Judicious use of labels means our course topics don't have to be simply a long list of resources. Remember to treat labels as a way of leading the student towards and into a resource. Labels are not designed for content, so try to keep labels short—perhaps two or three sentences at the most. Labels are like the glue that holds topics together. You don't want your glue to be too thick.

It's looking better, but my topic is still looking a little flat. You can indent your resources by clicking on the Move right icon next to the resource:

Below is how things now look with a little indenting:

Seeing the course from a student's point of view
As a teacher, you will see a lot of options on the screen that your students won't. To get a clear idea of how a student will see the course, use the Switch role to… option at the top right of the screen. Choose Student from this list, and you will see the course as students see it.
When you're done, click Return to my normal role and you'll get your normal view back. You will also need to Turn editing on to get the edit controls back.


Moodle Course Conversion: Beginner's Guide

Moodle Course Conversion: Beginner's Guide Taking existing classes online quickly with the Moodle LMS

* No need to start from scratch! This book shows you the quickest way to start using Moodle and e-learning, by bringing your existing lesson materials into Moodle.
* Move your existing course notes, worksheets, and resources into Moodle quickly then improve your course, taking advantage of multimedia and collaboration.
* Moving marking online – no more backbreaking boxes of assignments to lug to and from school or college.
* Requires no prior knowledge of Moodle; but even experienced Moodlers will find this useful for converting 'paper' resources and face-to-face lessons into Moodle.

http://www.packtpub.com/moodle-course-conversion/book

Hypnotic HTML—Finessing to Your Web Pages and Descriptions

You can see that my Getting Things Flying topic is still mostly words. The only pictures I have in there are the Moodle icons, used to indicate the resource or activity type. I really want to liven it up with pictures and animations, but where can I get the graphics from and what's the best way of including them?
Finding Decorative Images

The Internet has some fantastic resources for free images to include in our courses. Here are just a few of the more popular ones...
Google Image Search

...is great for finding a picture on just about anything. Be careful about copyright (more on that later). The pictures are of mixed quality and you have to be prepared to hunt around. But they are good fun and wonderful for livening up an otherwise dry course.

Visit http://images.google.com/ for the Google Image Search main page.

I'm going to look for a picture of a do-it-yourself rocket. I type in the words "DIY Rocket" into the search box and hit the Search Images button. I'm presented with a page full of miniature versions of the original pictures Google has found:

Next, if you want to, you go to the web page containing the full sized version. Then, right click on the image to save it (if you're happy with the thumbnail then you can save that instead). Firefox has the slight edge here, as Internet Explorer only allows you to save an image either in the format it is already, or as a BMP (bitmap). It is a good idea to speak to your technician or IT help desk about converting any images you save in this way to a JPEG(if it isn't already) or PNG.

Once you've saved the image on your computer and converted it to a suitable format (JPEG or PNG), then you need to upload it to, and include it in, your course.

Of course, other image search websites are available. AltaVista (www.altavista.com/image/) is another good search tool for images because it also allows you to search for images that are a specific size.
Flickr

...holds quality original photography, and you can restrict the search to creative commons so you don't have to worry about copyright issues. You're relying on someone else posting a picture of something you are interested in, but if you find one the quality is usually excellent. For example, there are plenty of rocket images taken by many amateur enthusiasts—who are also enthusiastic photographers. Once you've found your image, then you can right-click on it to save it.
General Clipart Libraries

Line drawings, stick figures, and more. Usually, good quality but you oft en find yourself trawling through a good many unimaginative images before you find a good one. A free and frequently used clip art resource is from Discovery Education (http://school.discoveryeducation.com). The discovery education site contains a comprehensive clipart gallery, all from the pen of illustrator Mark A. Hicks (I'm specifically citing Mark's work because it is where the image of the rocket in Topic 0 of my course came from).

www.alamy.com is another huge resource of 'royalty free' images that is well worth a visit.
Microsoft Office Clipart Library

Microsoft has packed a fantastic range of clip art images into Office. So in Word 2003, for example, click on Insert in the main menu, slide down to Picture and then slide across to Clip Art... to open the Clip Art side bar. My search in there for "rocket" found me a myriad of clip art images, actual pictures, and animations. You can limit your search to specific types of media. To add the clip art to your document, simply double-click on the thumbnail. This way, we can put together a single document just containing the clip art images we need for our course.

Now, we've got our clip art gathered together in a Word document, what's the best way of grabbing the images? You've got the same problem if you already have a document, or a PowerPoint presentation, that contains an image (including animated pictures) you want to grab...
Time for Action – Grab an Image from a Word Document

1. In Word 2003, select File from the main menu and slide down to Save As... The Save As dialog is displayed.
2. At the bottom of the Save As dialog, click on the Save as type: drop-down list. SelectWeb Page, Filtered (*.htm; *.html).
3. Make sure you are happy that Word is about to save your document to the right folder and that you are happy with the name. Press the Save button.
4. Don't worry about what the next dialog says. Click Yes.
5. Go to the folder you just saved your document to. In there, you should find a folder ending with "_files". In there, will be your images:

What Just Happened?

Oft en you'll already have a Word document or a PowerPoint presentation containing an image that you want to include in your course. We've just created a new Word document, collected images from the Office clip art library, and then we've seen how easy it is to grab images by saving the document as a web page. You can easily do the same for PowerPoint presentations.
Copyright Caution

Let's take a look at the copyright issues.

Because we are working in the education sector, and as long as we aren't planning on making money out of someone else's pictures, copyright shouldn't be that much of a problem. In fact, I've never had a problem with copyright—if it isn't obvious what you can and can't copy off a website then all you have to do is ask the copyright holder. In my experience, asking for images from the larger corporations oft en prompts them to send you even more images. If you still aren't sure, and are fortunate enough to have a librarian working in your establishment then they should be aware of what you can and can't copy and how it can be used.

Another issue to think about is that of including photographs of staff and students (or just people generally). Will you need their permission to include their likeness in your course?
HTML Editor Tips and Tricks—Smilies and Other Gimmicks

If you really want to set your course apart from the crowd and you are looking for the right tool to do it, then look no further than the HTML Editor we have been using all along. The Editor does a good job of making it very easy for us to improve the look and feel of our courses, and in helping us to create engaging Moodle pages. Let's spend the rest of this section spending a little time exploring some new ideas.
Smilies

Have you checked out the Insert Smiley button yet? It's a really simple way of putting a little bit of expression in your text. Want to be sarcastic but you don't want students to get the wrong end of the stick? Add a:

Want to show how happy you are? Insert a:

Just the inclusion of a few little graphics like this helps to give our courses a much more friendly face, because, let's face it, oft en students are put off by seeing too many words. Here's one way of remedying that problem...
Create Imaginary Dialog

Turn your course into a story and have a dialog between the characters. Imagine that there's an emergency in space...



Arranging Your HTML

While I've been bus y sorting and arranging the thought struck me that up to now, I haven't given much thought to how text and pictures are arranged on a page (although that thought may well have struck you). At the moment, I've got text then pictures, text then pictures, one under the other. It doesn't have to be so, because I can also arrange my pictures side-by-side using borderless tables:

Time for Action—Displaying Things Side by Side

1. After you have created a new web page, we first need to insert a table. Click on the Insert Table butt on to display the Insert Table dialog:

2. You can now specify the number of columns and rows your table will have. Don't worry if you aren't exactly sure how many you will need as you can always change things later on. I'm going to have two pictures side by side, each with a fragment of text underneath. That means two rows and two columns. When you first insert a table, the border has a thickness of 1. If you want a borderless table, then you must set the border to be 0.
3. Insert an image into each of the two cells in the top row of the new table:

4. If you want a full view of the page so that you can position the images then remember you can click on the Enlarge Editor button to open the Fullscreen view. Click on that button now.
5. The Fullscreen editor window opens. You will see a new row of buttons in the Fullscreen editor. (These are specifically for configuring tables. They only appear in the Fullscreen editor.)

6. Those additional butt on s help to configure the table so that the images are positioned where you want them. Try experimenting with those buttons now. Remember: you won't break anything!
7. I'm then going to enter some text into the cells underneath each picture and that's it! I'm done:

What Just Happened?

By using borderless tables to arrange our HTML, we can vastly improve the visual appeal of our web pages. Rather than having text, then a picture, then text, then a picture repeated down the page, we can arrange items in cells in a table which, as we have seen, is very easy to add in. It's also easy to reconfigure the table later on, if you find that your content needs to change.

Remember: when you first insert a table, the border has a thickness of 1. If you want a borderless table, then you must set the border to be 0.

Getting Animated—Add a Talking Character

Multi media these days isn't just limited to audio and video. How about having your own custom designed animated character included in your course? Not for everyone but a good deal of fun is the free online service Voki.

Voki characters are animated, on-screen avatars that can talk—either using computer generated speech, or from a recording or uploaded file. Check out http://www.voki.com for more information.

You will ultimately need to create a Voki.com account, but if you visit Voki.com, you can start creating an animated character straight away. Voki provides you with a fragment of web page code, and we can embed that code into any HTML we add to our course.

Showing you how to create a Voki character is beyond the scope of this article, but the Voki website contains lots of guidance on how to do this.

In the following screenshot, I've edited the Topic 0 summary and added in a Voki of me (kind of!) giving out an important safety warning:

HTML Blocks—A Bit on the Side

Let's use an HTML block to create a welcome message for our students.
Time for Action – Add a Welcome Message

1. Making sure you've got editing turned on, scroll down the course main page and look for the Blocks Add... block, usually under the last block on the right-hand side of the page:

2. Click on Add... and select HTML from the list. Moodle will add a new HTML block to the page:

3. To configure the new HTML block, click on the Configuration icon:

4. ... and you're taken to the Configuring an HTML block page. Give your new block a title and then add in your content. When you're done, press the Save changes butt on. Here's my new welcome message (including an animated GIF):

5. But a welcome message is no good hiding down in the bottom right-hand corner of my course main page. Let's move it to the top left using the Move left and Move up icons:

6. Click on the move icons and I can get my message positioned just where I want it:

What Just Happened?

We've added a new HTML block to the course main page to provide a welcome message to our students. Any HTML can be added in there. What's great is that you can add as many HTML blocks to your course front page as you like…
Summary

In this article, we have covered:

* Arranging resources within topics to make topics look more visually appealing. We used the Label resource as the glue to holds resources together.
* We took a comprehensive look at tips and tricks we can use to make our courses more engaging for students.
* We included an animated character using Voki.com—more practice at using embeddable code. Other free, animated characters are available(e.g. http://gizmoz.com).
* We used an HTML block to provide a welcome message to our students.


Moodle Course Conversion: Beginner's Guide

Moodle Course Conversion: Beginner's Guide Taking existing classes online quickly with the Moodle LMS

* No need to start from scratch! This book shows you the quickest way to start using Moodle and e-learning, by bringing your existing lesson materials into Moodle.
* Move your existing course notes, worksheets, and resources into Moodle quickly then improve your course, taking advantage of multimedia and collaboration.
* Moving marking online – no more backbreaking boxes of assignments to lug to and from school or college.
* Requires no prior knowledge of Moodle; but even experienced Moodlers will find this useful for converting 'paper' resources and face-to-face lessons into Moodle.

http://www.packtpub.com/moodle-course-conversion/book

About the Author

Ian Wild

A physicist by profession, Ian's career has always focused primarily on communication and learning.

Fifteen years spent in private industry designing communication systems software eventually saw Ian concentrate on the development of accessibility and learning aids for blind, partially sighted, dyslexic, and dyscalculic computer users – whilst also working part-time as a math and science tutor.

Teaching only part-time meant not spending as much time with his students as he would have wanted. This and his background in learning and communication technology seeded his interest in virtual learning environments.
Books from Packt

Building Websites with Joomla! 1.5
Building Websites with Joomla! 1.5


Moodle 1.9 E-Learning Course Development
Moodle 1.9 E-Learning Course Development


Moodle Administration
Moodle Administration


Building Powerful and Robust Websites with Drupal 6
Building Powerful and Robust Websites with Drupal 6


Moodle Teaching Techniques
Moodle Teaching Techniques


Alfresco Developer Guide
Alfresco Developer Guide


OpenCms 7 Development
OpenCms 7 De

2007-03-16

WebBrowser Customization

This tutorial shows you several ways to customize the "out of the box" behavior and appearance of the WebBrowser Control. You'll see how to use the advanced hosting interfaces IDocHostUIHandler, IDocHostUIHandler2, IDocHostShowUI, and ICustomDoc. This article will also look at other customization techniques such as download control through handling DISPID_AMBIENT_DLCONTROL in the host's IDispatch implementation, and using IHostDialogHelper.

This article is divided into the following sections:

Prerequisites and Requirements

In order to understand and use this tutorial, you need:

  • A good understanding of C++ and the Component Object Model (COM).
  • Familiarity with the Active Template Library (ATL).
  • Microsoft Internet Explorer 6 or later installed.
  • Header files and libraries for Internet Explorer 6 or later for use in your development environment; in particular, you need Mshtmhst.h.

Many of the WebBrowser customization features have been available since Internet Explorer 5 and Internet Explorer 5.5. Only a couple require Internet Explorer 6. One more requires Internet Explorer 6 for Microsoft Windows XP Service Pack 2 (SP2). Check the reference documentation for versioning information.

Introduction

Hosting the WebBrowser Control is a powerful tool for rapid application development. Through hosting, you can leverage easy-to-use technologiesDynamic HTML (DHTML), HTML, and XMLfor displaying content and developing a user interface (UI). However, "out of the box," the WebBrowser Control may not behave quite the way you want. For instance, in its default state the user can view the source of a displayed page by right-clicking and choosing the View Source option on the shortcut menu. You might want to disable or eliminate that option. You might also want to go even further and replace the default shortcut menu entirely with your own custom menu.

Aside from the customizations just mentioned, the advanced hosting features of Internet Explorer enable you to:

  • Use buttons and other controls on a displayed page to call internal methods in your application, effectively extending the DHTML Object Model.
  • Change drag-and-drop behavior.
  • Control which pages your application can access, restricting navigation, for example, to specify pages, domains, or sites.
  • Intercept user keystrokes and process them however you want. For example, you might intercept CTRL+O to prevent the user from opening a new page in Internet Explorer rather than the host application.
  • Change default font and display settings.
  • Control the kinds of content that are downloaded and what the WebBrowser Control does with them once they are downloaded. For example, you can prevent videos from playing, script from running, or new windows from opening when users click on links, or prevent Microsoft ActiveX controls from downloading or executing.
  • Restrict View Source.
  • Capture searches.
  • Capture navigation errors.
  • Replace or modify shortcut menus and shortcut menu entriesdisabling, replacing, customizing, or adding to them.
  • Change registry settings for your application.
  • Intercept and change messages dialogs shown by the WebBrowser Control.
  • Control how new windows are created.

In the following sections, we'll look at many, though not all, of these possibilities and discuss how to implement them.

WebBrowser Customization Architecture

Introducing IDocHostUIHandler, IDocHostUIHander2, IDocHostShowUI, and ICustomDoc

Three interfaces are at the heart of WebBrowser ControlUI customization: IDocHostUIHandler, IDocHostUIHandler2, and IDocHostShowUI. These are interfaces that you implement in your application when you want to modify the WebBrowser Control. There are also a couple of service interfaces. ICustomDoc is implemented by MSHTML and provides a means to enable WebBrowser Control customization in some scenarios. IHostDialogHelper provides a means to open trusted dialog boxes, without identification that marks them as Internet Explorer dialog boxes.

In addition to using these interfaces, there are two other things you can do. For one, you can control download by intercepting ambient property changes in your IDispatch implementation. Second, you can control how new windows are created by intercepting DISPID_NEWWINDOW2 in your IDispatch implementation.

How It Works

The mechanism for WebBrowser Control customization is designed to be automated when a container provides support for ActiveX controls. Whenever the WebBrowser Control is instantiated, it attempts to find IDocHostUIHandler, IDocHostUIHandler2 and IDocHostShowUI implementations from the host, if they are available. The WebBrowser Control does this by a QueryInterface call on the host's IOleClientSite interface.

This architecture works automatically for an application that implements an IOleClientSite interface and that passes an IOleClientSite pointer to the WebBrowser Control through the browser's IOleObject::SetClientSite method. A typical instantiation of the WebBrowser Control might look like this:

SetClientSite(this;">// Error checking omitted for clarity
CComPtr spOleObj;

// Create WebBrowser--store pointer in class member variable m_spWebBrowser
CoCreateInstance(CLSID_WebBrowser, NULL, CLSCTX_INPROC, IID_IWebBrowser2, (void**)&m_spWebBrowser);

// Query WebBrowser for IOleObject pointer
m_spWebBrowser->QueryInterface(IID_IOleObject, (void**)&spOleObj);

// Set client site
spOleObj->SetClientSite(this);

// In-place activate the WebBrowser control
RECT rcClient
GetClientRect(&rcClient);
spOleObj->DoVerb(OLEIVERB_INPLACEACTIVATE, NULL, this, 0, GetTopLevelWindow(), &rcClient);

// Register container to intercept WebBrowser events
AtlAdvise(m_spWebBrowser, GetUnknown(), DIID_DWebBrowserEvents2, &m_dwCookie);

// Navigate to start page
m_spWebBrowser->Navigate(L"res://webhost.exe/startpage.htm", NULL, NULL, NULL, NULL);

However, if your application doesn't have an IOleClientSite interface, all is not lost. Internet Explorer provides the ICustomDoc interface so you can pass Internet Explorer your IDocHostUIHandler interface yourself. You cannot use IDocHostUIHandler2 and IDocHostShowUI without providing an IOleClientSite interface on the object hosting the WebBrowser Control.

When the WebBrowser Control holds a pointer to any of these interfaces, the methods of the interfaces are called at appropriate times during the lifetime of the WebBrowser Control. For instance, when the user right-clicks with the mouse anywhere in the WebBrowser Control's client area, your implementation of IDocHostUIHandler::ShowContextMenu will be called before Internet Explorer displays its default shortcut menu. This gives you a chance to display your own shortcut menu and prevent Internet Explorer from displaying its menu.

There are a few more important points to remember when initializing the WebBrowser Control. Your application should use OleInitialize rather than CoInitialize to start COM. OleInitialize enables support for the Clipboard, drag-and-drop operations, OLE, and in-place activation. Use OleUninitialize to close the COM library when your application shuts down.

The ATLCOM Wizard uses CoInitialize rather than OleInitialize to open the COM libraries. If you use this wizard to build an executable program, you need to change the CoInitialize and CoUninitialize calls to OleInitialize and OleUninitialize. For a Microsoft Foundation Classes (MFC) application, be sure that your application calls AfxOleInit, which calls OleInitialize, in its initialization process.

If you don't want drag-and-drop support in your application, you can call IWebBrowser2::RegisterAsDropTarget, passing in VARIANT_TRUE, to prevent any drag-and-drop operations on your WebBrowser Control instance.

An application hosting the WebBrowser Control will also need an implementation of IOleInPlaceSite, and since IOleInPlaceSite derives from IOleWindow, the application will also need an implementation of IOleWindow. You need these implementations so your application has a window in which to display the WebBrowser Control and so you can manage its display.

The implementations of these interfaces and IOleClientSite can be minimal or nonexistent in many cases. The IOleClientSite methods can all return E_NOTIMPL. Some of the IOleInPlaceSite and IOleWindow methods need an implementation beyond their return value. See the code sample for an example of a minimal implementation of IOleInPlaceSite and IOleWindow.

Now that we have covered the initialization preliminaries, let's take a look at each of the interfaces for WebBrowser Control customization.

IDocHostUIHandler

IDocHostUIHandler has been available since Internet Explorer 5. It provides fifteen methods. In general, some of the more important methods are IDocHostUIHandler::GetExternal, IDocHostUIHandler::GetHostInfo, IDocHostUIHandler::GetOptionKeyPath, IDocHostUIHandler::ShowContextMenu, and IDocHostUIHandler::TranslateAccelerator. Of course, the methods that are most important to you will depend on your application.

IDocHostUIHandler::GetHostInfo

You use IDocHostUIHandler::GetHostInfo to tell MSHTML about your application's capabilities and requirements. With it you can control a variety of things, for instance:

  • You can disable the browser's 3-D border.
  • You can prevent scroll bars or change their appearance.
  • You can define how you want to handle double-clicks.

IDocHostUIHandler::GetHostInfo has one parameter, a pointer to a DOCHOSTUIINFO structure allocated by MSHTML. Your job is to fill this structure with the information you want to pass to MSHTML.

There are four members in the DOCHOSTUIINFO structure. The first member is cbSize, which is the size of the structure. You should set this yourself as the following code sample shows. The second member is dwFlags, which can take any number of flag values, combined with the bitwise OR operator, from the DOCHOSTUIFLAG enumeration. The third member is dwDoubleClick, which takes a value from the DOCHOSTUIDBLCLK enumeration. The fourth member is pchHostCss. You can set pchHostCss to a pointer to a string with Cascading Style Sheets (CSS) rules that you want to apply globally to any page displayed in the WebBrowser control. The final member of DOCHOSTUIINFO is pchHostNs. This is also a string pointer with which you can provide a semicolon-delimited list of namespaces. Use this member when you use custom tags on the pages you're displaying in the WebBrowser Control. This way you can have a global declaration for namespaces and don't have to declare them on each displayed page.

Be sure to use CoTaskMemAlloc to allocate strings for pchHostCss or pchHostNS.

HRESULT GetHostInfo(DOCHOSTUIINFO *pInfo)
{
WCHAR* szCSS = L"BODY {background-color:#ffcccc}";
WCHAR* szNS = L"IE;MyTags;MyTags2='www.microsoft.com'";

#define CCHMAX 256
size_t cchLengthCSS, cchLengthszNS;

HRESULT hr = StringCchLengthW(szCSS, CCHMAX, &cchLengthCSS);
// TODO: Add error handling code here.
OLECHAR* pCSSBuffer = (OLECHAR*)CoTaskMemAlloc((cchLengthCSS + 1) * sizeof(OLECHAR));
// TODO: Add error handling code to make sure memory block was allocated successfully.

hr = StringCchLengthW(szNS, CCHMAX, &cchLengthszNS);
// TODO: Add error handling code here.
OLECHAR* pNSBuffer = (OLECHAR*)CoTaskMemAlloc((cchLengthszNS + 1) * sizeof(OLECHAR));
// TODO: Add error handling code to make sure memory block was allocated successfully.

hr = StringCchCopyW(pCSSBuffer, cchLengthCSS + 1, szCSS);
// TODO: Add error handling code here.
hr = StringCchCopyW(pNSBuffer, cchLengthszNS + 1, szNS);
// TODO: Add error handling code here.

pInfo->cbSize = sizeof(DOCHOSTUIINFO);
pInfo->dwFlags = DOCHOSTUIFLAG_NO3DBORDER | DOCHOSTUIFLAG_SCROLL_NO;
pInfo->dwDoubleClick = DOCHOSTUIDBLCLK_DEFAULT;
pInfo->pchHostCss = pCSSBuffer;
pInfo->pchHostNS = pNSBuffer;

return S_OK;
}

If you have nothing special to say to MSHTML, you can return E_NOTIMPL from this method.

IDocHostUIHandler::ShowContextMenu

By implementing this method, you gain control over the shortcut menus displayed by the WebBrowser Control when a user right-clicks. You can prevent Internet Explorer from displaying its default menu by returning S_OK from this method. Returning some other value, like S_FALSE or E_NOTIMPL, allows Internet Explorer to go ahead with its default shortcut menu behavior.

If you return S_OK from this method and nothing more, you can prevent any right-click behavior by the WebBrowser Control. This may be all you desire in many scenarios but you can do more. Often, you use this method to create and display your own shortcut menu before returning S_OK. If you know the resources from which the WebBrowser Control displays its menus, and how it chooses them, you can also effectively customize the default WebBrowser Control shortcut menus themselves.

Refer to WebBrowser Customization (Part 2) for an implementation example of this method.

IDocHostUIHandler::GetExternal: Extending the DOM

IDocHostUIHandler provides you with a means to extend the Internet ExplorerDocument Object Model (DOM) with objects, methods, and properties of your own, implemented in your own application. You do this by providing MSHTML a pointer to the IDispatch interface for the COM automation object that implements your custom object, properties, and methods. These objects, properties, and methods will then be available to any page displayed in the WebBrowser Control through the document's external object.

You can easily implement this method, assuming your IDispatch interface is on the same object that implements IDocHostUIHandler.

HRESULT CBrowserHost::GetExternal(IDispatch **ppDispatch)
{
*ppDispatch = this;
return S_OK;
}

Once MSHTML has a pointer to your IDispatch, MSHTML will pass any calls on Web pages to automation methods on your application through the external object:


You can also use this technique to pass whole objects to a page. To do this, create a method in your IDispatch implementation that passes back the object you want to make available.


See the sample application for an example of IDispatch automation implementation using ATL.

IDocHostUIHandler::GetOptionKeyPath

IDocHostUIHandler::GetOptionKeyPath is a very powerful tool for customizing the WebBrowser Control. Many of the WebBrowser Control display and behavior settings are stored in the registry under the HKEY_CURRENT_USER key. IDocHostUIHandler::GetOptionKeyPath gives you an opportunity to override these registry settings for your specific instance of the WebBrowser Control. It does this by letting you supply an alternate registry location from which the WebBrowser Control will read in registry settings.

An implementation of IDocHostUIHandler::GetOptionKeyPath passes a string to the WebBrowser Control for the registry location you want it to read from. The WebBrowser Control will look for this key under the HKEY_CURRENT_USER key.

HRESULT CBrowserHost::GetOptionKeyPath(LPOLESTR *pchKey,
DWORD dwReserved)
{
HRESULT hr;

#define CCHMAX 256
size_t cchLength;

if (pchKey)
{
WCHAR* szMyKey = L"Software\\MyCompany\\MyApp";
hr = StringCchLengthW(szMyKey, CCHMAX, &cchLength);
// TODO: Add error handling code here.

*pchKey = (LPOLESTR)CoTaskMemAlloc((cchLength + 1) * sizeof(WCHAR));
if (*pchKey)
hr = StringCchCopyW(*pchKey, cchLength + 1, szKey);
// TODO: Add error handling code here.

hr = (*pchKey) ? S_OK : E_OUTOFMEMORY;
}
else
hr = E_INVALIDARG;

return hr;
}

As with IDocHostUIHandler::GetHostInfo, be sure to allocate memory for your strings using CoTaskMemAlloc.

Telling the WebBrowser Control where to look for your registry settings is the first stepactually, it's the second step as far as program execution is concerned. Your program must set the keys at the location specified by IDocHostUIHandler::GetOptionKeyPath so the WebBrowser Control can read them. There are a variety of ways to do this. One way would be with a registry script that runs when the application is installed. Another way might be to do it programmatically when the application starts. Here's a function that sets keys to change the default font, size, and color.

HRESULT SetSomeKeys()
{
HKEY hKey = NULL;
HKEY hKey2 = NULL;
HKEY hKey3 = NULL;
DWORD dwDisposition = NULL;
LONG lResult = NULL;
#define CBMAX 256
size_t cbLength;

RegCreateKeyEx(HKEY_CURRENT_USER, _T("Software\\MyCompany\\MyApp"),
NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE,
NULL, &hKey, &dwDisposition);

RegCreateKeyEx(hKey, _T("Main"), NULL, NULL, REG_OPTION_NON_VOLATILE,
KEY_SET_VALUE, NULL, &hKey2, &dwDisposition);

RegSetValueEx(hKey2, _T("Use_DlgBox_Colors"), NULL, REG_SZ,
(CONST BYTE*)_T("no"), sizeof(_T("no")));

RegCloseKey(hKey2);

RegCreateKeyEx(hKey, _T("Settings"), NULL, NULL, REG_OPTION_NON_VOLATILE,
KEY_SET_VALUE, NULL, &hKey2, &dwDisposition);

RegSetValueEx(hKey2, _T("Anchor Color"), NULL, REG_SZ,
(CONST BYTE*)_T("0,255,255"), sizeof(_T("0,255,255")));

RegSetValueEx(hKey2, _T("Text Color"), NULL, REG_SZ,
(CONST BYTE*)_T("255,0,255"), sizeof(_T("255,0,255")));

RegCloseKey(hKey2);

RegCreateKeyEx(hKey, _T("International\\Scripts"), NULL, NULL,
REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL,
&hKey2, &dwDisposition);

BYTE bDefaultScript = 0x3;

RegSetValueEx(hKey2, _T("Default_Script"), NULL, REG_BINARY,
&bDefaultScript, sizeof(bDefaultScript));

RegCreateKeyEx(hKey2, _T("3"), NULL, NULL, REG_OPTION_NON_VOLATILE,
KEY_SET_VALUE, NULL, &hKey3, &dwDisposition);

BYTE bSize = 0x4; // Value from 0 - 4. 2 is medium.
TCHAR* szFontName = _T("Comic Sans MS");
TCHAR* szFixedFontName = _T("Courier");

HRESULT hr = StringCbLength(szFontName, CBMAX, &cbLength);
// TODO: Add error handling code here.
RegSetValueEx(hKey3, _T("IEPropFontName"), NULL, REG_SZ,
(CONST BYTE*)szFontName, cbLength + sizeof(TCHAR));

hr = StringCbLength(szFixedFontName, CBMAX, &cbLength);
// TODO: Add error handling code here.
RegSetValueEx(hKey3, _T("IEFixedFontName"), NULL, REG_SZ,
(CONST BYTE*)szFixedFontName, cbLength + sizeof(TCHAR));

RegSetValueEx(hKey3, _T("IEFontSize"), NULL, REG_BINARY, &bSize, sizeof(bSize));

RegCloseKey(hKey3);
RegCloseKey(hKey2);
RegCloseKey(hKey);

return S_OK;
}

IDocHostUIHandler2

IDocHostUIHandler2 has a single method, IDocHostUIHandler2::GetOverrideKeyPath. It performs a function very similar to IDocHostUIHandler::GetOptionKeyPath. It points your hosted WebBrowser to registry settings to modify the default Internet Explorer registry settings. An implementation of IDocHostUIHandler2::GetOverrideKeyPath will look much the same as an implementation of IDocHostUIHandler::GetOptionKeyPath.

GetOptionKeyPath and GetOverrideKeyPath Compared

The difference between IDocHostUIHandler::GetOptionKeyPath and IDocHostUIHandler2::GetOverrideKeyPath is subtle, but significant. If you implement IDocHostUIHandler::GetOptionKeyPath, your WebBrowser Control instance will ignore any user settings for Internet Explorer. These settings are stored in the registry under HKEY_CURRENT_USER/Software/Microsoft/Internet Explorer. If you implement IDocHostUIHandler2::GetOverrideKeyPath, your WebBrowser Control instance will incorporate any user settingsfont settings, menu extensions, and so forthinto the way it displays and behaves.

To illustrate the difference between IDocHostUIHandler::GetOptionKeyPath and IDocHostUIHandler2::GetOverrideKeyPath, refer to the code example for adding extensions to the context menu in WebBrowser Customization (Part 2). Recall the line:

spCT->Exec(&CGID_ShellDocView, SHDVID_ADDMENUEXTENSIONS, 0, &amp;var1, &var2);

If you've implemented IDocHostUIHandler::GetOptionKeyPath, this line would add none of the menu extension information that is stored in the registry for the current user. Instead, it would only add menu items that you have created. If you've implemented IDocHostUIHandler2::GetOverrideKeyPath, this line would add any extensions defined for the current user under HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\MenuExt unless you explicitly supply an empty or alternative MenuExt key in your custom registry key.

Controlling Navigation

You may have wondered why the section on IDocHostUIHandler didn't mention IDocHostUIHandler::TranslateUrl as a method to implement when you wish to control page navigation. The reason is that this method is not the most general purpose technique with which to control navigation. Unless you are hosting MSHTML directly, this method will have no effect on navigation. Instead, you can control navigation by implementing your IDispatch::Invoke method to handle DISPID_BEFORENAVIGATE2. As an example, the following code prevents navigation to a particular URL, displaying a "No Navigation Allowed" error page if the user attempts to do so.

case DISPID_BEFORENAVIGATE2:
{
CComBSTR url = ((*pDispParams).rgvarg)[5].pvarVal->bstrVal;
if (url == "http://www.adatum.com" || url == "http://www.adatum.com/")
{
CComPtr spBrowser;
CComPtr spDisp = ((*pDispParams).rgvarg)[6].pdispVal;
spDisp->QueryInterface(IID_IWebBrowser2, (void**)&spBrowser);
spBrowser->Stop();
CComBSTR newURL = "L"res://webhost.exe/nonavigate.htm";
spBrowser->Navigate(newURL, NULL, NULL, NULL, NULL);
((*pDispParams).rgvarg)[0].boolVal = TRUE;
}
break;
}

IDocHostShowUI

This interface gives you control over the message boxes and help files displayed by the WebBrowser Control. It works the same way as IDocHostUIHandler and IDocHostUIHandler2 in that you implement it so the WebBrowser Control can call your IDocHostShowUI methods before it displays any messages or help menus of its own. This gives you a chance to prevent the WebBrowser Control from displaying anything and enables you to display your own custom message or help instead. IDocHostShowUI has two methods, IDocHostShowUI::ShowMessage and IDocHostShowUI::ShowHelp.

IDocHostShowUI::ShowMessage

Return S_OK to disable WebBrowser Control messages. Any other return value, like S_FALSE or E_NOTIMPL, allows the WebBrowser Control to display with its message box.

One nice thing you can do with this method is customize the message box captions for your application so they don't read "Microsoft Internet Explorer." You can do this by comparing the caption string in lpstrCaption with the string resource Internet Explorer uses, which is stored in Shdoclc.dll. It is identified by the symbol IDS_MESSAGE_BOX_TITLE, whose value is 2213. The following code snippet shows how you might do this.

HRESULT CBrowserHost::ShowMessage(HWND hwnd,
LPOLESTR lpstrText,
LPOLESTR lpstrCaption,
DWORD dwType,
LPOLESTR lpstrHelpFile,
DWORD dwHelpContext,
LRESULT *plResult)
{
USES_CONVERSION;
TCHAR pBuffer[50];

// resource identifier for window caption "Microsoft Internet Explorer"
#define IDS_MESSAGE_BOX_TITLE 2213

// Load Shdoclc.dll and the IE message box title string
HINSTANCE hinstSHDOCLC = LoadLibrary(TEXT("SHDOCLC.DLL"));

if (hinstSHDOCLC == NULL)
{
// Error loading module -- fail as securely as possible
return;
}
LoadString(hinstSHDOCLC, IDS_MESSAGE_BOX_TITLE, pBuffer, 50);

// Compare the IE message box title string with lpstrCaption
// If they're the same, substitute your own Caption
if (_tcscmp(OLE2T(lpstrCaption), pBuffer) == 0)
lpstrCaption = L"Custom Caption";

// Create your own message box and display it
*plResult = MessageBox(OLE2T(lpstrText), OLE2T(lpstrCaption), dwType);

// Unload Shdoclc.dll and return
FreeLibrary(hinstSHDOCLC);
return S_OK;
}
security note Security Alert Using LoadLibrary incorrectly can compromise the security of your application by loading the wrong DLL. Refer to the LoadLibrary documentation for information on how to correctly load DLLs with different versions of Windows.

IDocHostShowUI::ShowHelp

This method is called whenever Internet Explorer Help would be shown, for instance when the F1 key is pressed, and works analogously to IDocHostShowUI::ShowMessage. Return S_OK to override Internet Explorer Help, or another HRESULT value to let Internet Explorer proceed with its Help.

Controlling Download and Execution

The WebBrowser Control gives you control over what it downloads, displays, and executes. To gain this control, you need to implement your host's IDispatch so it handles DISPID_AMBIENT_DLCONTROL. When the WebBrowser Control is instantiated, it will call your IDispatch::Invoke with this ID. Set pvarResult to a combination of following flags, using the bitwise OR operator, to indicate your preferences.

  • DLCTL_DLIMAGES, DLCTL_VIDEOS, and DLCTL_BGSOUNDS: Images, videos, and background sounds will be downloaded from the server and displayed or played if these flags are set. They will not be downloaded and displayed if the flags are not set.
  • DLCTL_NO_SCRIPTS and DLCTL_NO_JAVA: Scripts and Java applets will not be executed.
  • DLCTL_NO_DLACTIVEXCTLS and DLCTL_NO_RUNACTIVEXCTLS : ActiveX controls will not be downloaded or will not be executed.
  • DLCTL_DOWNLOADONLY: The page will only be downloaded, not displayed.
  • DLCTL_NO_FRAMEDOWNLOAD: The WebBrowser Control will download and parse a frameSet, but not the individual frame objects within the frameSet.
  • DLCTL_RESYNCHRONIZE and DLCTL_PRAGMA_NO_CACHE: These flags cause cache refreshes. With DLCTL_RESYNCHRONIZE, the server will be asked for update status. Cached files will be used if the server indicates that the cached information is up-to-date. With DLCTL_PRAGMA_NO_CACHE, files will be re-downloaded from the server regardless of the update status of the files.
  • DLCTL_NO_BEHAVIORS: Behaviors are not downloaded and are disabled in the document.
  • DLCTL_NO_METACHARSET_HTML: Character sets specified in meta elements are suppressed.
  • DLCTL_URL_ENCODING_DISABLE_UTF8 and DLCTL_URL_ENCODING_ENABLE_UTF8: These flags function similarly to the DOCHOSTUIFLAG_URL_ENCODING_DISABLE_UTF8 and DOCHOSTUIFLAG_URL_ENCODING_ENABLE_UTF8 flags used with IDocHostUIHandler::GetHostInfo. The difference is that the DOCHOSTUIFLAG flags are checked only when the WebBrowser Control is first instantiated. The download flags here for the ambient property change are checked whenever the WebBrowser Control needs to perform a download.
  • DLCTL_NO_CLIENTPULL: No client pull operations will be performed.
  • DLCTL_SILENT: No user interface will be displayed during downloads.
  • DLCTL_FORCEOFFLINE: The WebBrowser Control always operates in offline mode.
  • DLCTL_OFFLINEIFNOTCONNECTED and DLCTL_OFFLINE: These flags are the same. The WebBrowser Control will operate in offline mode if not connected to the Internet.

DISPID_AMBIENT_DLCONTROL and the flag values are defined in mshtmdid.h.

Initially, when the function call to IDispatch::Invoke starts, the VARIANT to which the parameter pvarResult points is of type VT_EMPTY. You must switch the type to VT_I4 for any settings to have an effect. You can place your flag values in the lVal member of the VARIANT.

Most of the flag values have negative effects, that is, they prevent behavior that normally happens. For instance, scripts are normally executed by the WebBrowser Control if you don't customize its behavior. But if you set the DLCTL_NOSCRIPTS flag, no scripts will execute in that instance of the control. However, three flagsDLCTL_DLIMAGES, DLCTL_VIDEOS, and DLCTL_BGSOUNDSwork exactly opposite. If you set flags at all, you must set these three for the WebBrowser Control to behave in its default manner vis-a-vis images, videos and sounds.

The following code sample causes a WebBrowser Control instance to download and display images and videos, but not background sounds, since the DLCTL_BGSOUNDS is not explicitly set. Also, script execution on pages displayed by the WebBrowser Control is disabled.

STDMETHODIMP CAtlBrCon::Invoke(DISPID dispidMember, REFIID riid,
LCID lcid, WORD wFlags,
DISPPARAMS* pDispParams,
VARIANT* pvarResult,
EXCEPINFO* pExcepInfo,
UINT* puArgErr)
{
switch (dispidMember)
{
case DISPID_AMBIENT_DLCONTROL:
pvarResult->vt = VT_I4;
pvarResult->lVal = DLCTL_DLIMAGES | DLCTL_VIDEOS | DLCTL_NO_SCRIPTS;
break;

default:
return DISP_E_MEMBERNOTFOUND;
}

return S_OK;
}

IHostDialogHelper

IHostDialogHelper is an interface you can use to create dialog boxes according to your liking. This interface has one method, IHostDialogHelper::ShowHTMLDialog. This method provides the same service as the function ShowHTMLDialog, but it's a little easier to use.

To use IHostDialogHelper, you create the dialog helper object from scratch. Here's how you would do it using CoCreateInstance. The interface and IDs are defined in mshtmhst.h.

IHostDialogHelper* pHDH;
IMoniker* pUrlMoniker;
BSTR bstrOptions = SysAllocString(L"dialogHeight:30;dialogWidth:40");
BSTR bstrPath = SysAllocString(L"c:\\dialog.htm");

CreateURLMoniker(NULL, bstrPath, &pUrlMoniker);

// Create the dialog helper object
CoCreateInstance(CLSID_HostDialogHelper,
NULL,
CLSCTX_INPROC,
IID_IHostDialogHelper,
(void**)&pHDH);

// Call ShowHTMLDialog to create your dialog box
pHDH->ShowHTMLDialog(NULL,
pUrlMoniker,
NULL,
bstrOptions,
NULL,
NULL);

// Free resources
SysFreeString(bstrPath);
SysFreeString(bstrOptions);
pUrlMoniker->Release();
pHDH->Release();

Controlling New Windows

One important way to take control of the WebBrowser Control is to control navigation. You saw earlier how you can intercept DISPID_BEFORENAVIGATE2 in an IDispatch::Invoke implementation to control where your WebBrowser Control will navigate. Another important aspect of navigation is to control how the navigation occurs, especially when opening new windows. Let's say, for instance, that the user clicks the right mouse button over a link and chooses "Open in New Window" or that a page contains a script like this:

window.open("www.msn.com");

By default, the WebBrowser Control deals with this code by opening a new instance of Internet Explorer to display the page. This may be fine for your application. But then again, it may not. Perhaps you'll want all links to open in your current WebBrowser Control instance. Or perhaps you'll want to open a link in a new WebBrowser Control instance under your control, with your user interface and with your branding.

You can intercept an event, DWebBrowserEvents2::NewWindow2, in your IDispatch implementation to control this. Your control needs to connect to the DWebBrowserEvents2 connection point to intercept this event.

Once you're connected to DWebBrowserEvents2, implement your IDispatch::Invoke so that it handles DISPID_NEWWINDOW2. During the IDispatch::Invoke function call for DISPID_NEWWINDOW2, the array pDispParams contains two parameters. The first one, at index zero, is a Boolean value that tells the WebBrowser Control whether to cancel the new window or not. By default, it is FALSE and a new window will open. If you want to cancel new window creation completely, set the flag to TRUE.

The parameter at index one is a pointer to an IDispatch interface. You can set this parameter to the IDispatch of a WebBrowser Control that you've created. When you pass back an IDispatch like this, MSHTML will use the control you've given it to open the link.

Information Bar

Internet Explorer 6 for Windows XP SP2 introduced a new security UI element called the Information Bar. The Information Bar displays a UI element to users of Internet Explorer when certain actions are prevented. Specifically, it displays when the following are blocked.

  • Pop-up window instantiation (see Pop-up Blocker)
  • File downloads (see File Download Restrictions)
  • ActiveX control installation (see ActiveX Restrictions)
  • ActiveX control security prompts because of the user's security settings or because the control is not marked safe for scripting
  • Files that have a mismatch between the file extension and the MIME type (see MIME Handling)
  • Content restricted by the network protocol lockdown (see Protocols)

The Information Bar is one of the feature controls introduced in Internet Explorer 6 for Windows XP SP2. Like the other feature controls, it is managed through a registry key (FEATURE_SECURITYBAND). Internet Explorer (iexplorer.exe) and Windows Explorer (explorer.exe) run under this feature control by default. The following shows the registry key and enabled processes.

HKEY_LOCAL_MACHINE (or HKEY_CURRENT_USER)
SOFTWARE
Microsoft
Internet Explorer
Main
FeatureControl
FEATURE_SECURITYBAND
iexplorer.exe= 0x00000001
explorer.exe= 0x00000001
process name.exe=0x00000001

The FEATURE_SECURITYBAND feature control only affects whether Internet Explorer displays the Information Bar, which alerts the user that an action has been mitigated. It does not control the mitigation of the action.

An application hosting the WebBrowser Control can enable the Information Bar by adding its process to this registry key. This can be done programmatically by using the CoInternetSetFeatureEnabled function. If an application does not run under this feature control, the WebBrowser Control behaves the same as Internet Explorer 6 SP1b.

There is no access to this feature through script.

Applications running under the FEATURE_SECURITYBAND and related feature controls can also leverage the Information BarAPIs to customize the UI displayed when a URL action is disallowed. There are several new OLECMDID commands for the Information Bar. The first three are part of the CGID_DocHostCommandHandler group. Hosting applications should implement IOleCommandTarget on their implementation of IDocHostUIHandler to receive IOleCommandTarget::Exec calls from the WebBrowser Control.

  • OLECMDID_PAGEACTIONBLOCKED
  • OLECMDID_PAGEACTIONUIQUERY
  • OLECMDID_FOCUSVIEWCONTROLS

Hosting applications can use the following two new OLECMDID commands to make IOleCommandTarget::Exec calls on the WebBrowser Control.

  • OLECMDID_FOCUSVIEWCONTROLSQUERY
  • OLECMDID_SHOWPAGEACTIONMENU
This example uses IWebBrowser2::ExecWB to execute the OLECMDID_SHOWPAGEACTIONMENU command.
   POINT pt = { 0 };
GetCursorPos(&pt);

CComVariant varHwnd((LONG)hwnd);
CComVariant varX(pt.x);
CComVariant varY(pt.y);

SAFEARRAY* psa = SafeArrayCreateVector(VT_VARIANT, 0, 3);

LONG lIndex = 0;
SafeArrayPutElement(psa, &lIndex, &amp;varHwnd);
lIndex++;
SafeArrayPutElement(psa, &lIndex, &amp;varX);
lIndex++;
SafeArrayPutElement(psa, &lIndex, &amp;varY);

CComVariant varArgIn;
V_VT(&varArgIn) = VT_ARRAY | VT_I4;
V_ARRAY(&varArgIn) = psa;

pBrowser-<>*Fix pointer operator!!ExecWB(OLECMDID_SHOWPAGEACTIONMENU, (OLECMDEXECOPT)dwPageActionFlags, &varArgIn, NULL);

Also, an application can override the default security zone settings by implementing IInternetSecurityManager. See Implementing a Custom Security Manager for more information.

Conclusion

You now have a number of techniques at your disposal to customize the WebBrowser Control. This article is by no means exhaustive, but hopefully you also now have a sense of some of the possibilities you may discover on your own beyond the techniques in this article. Check out the Internet Explorer registry to see the kinds of information stored there that you can modify with IDocHostUIHandler::GetOptionKeyPath or IDocHostUIHandler2::GetOverrideKeyPath. Keep in mind that many registry settings are interdependent with others. You may have to do some experimentation to discover how particular registry settings can be customized effectively. You can also look into IDocHostUIHandler::GetDropTarget if you want to control what the WebBrowser Control does during drag-and-drop operations.

Part one of this tutorial introduced several of the standard hosting interfaces for the WebBrowser Control: IDocHostUIHandler, IDocHostShowUI, and ICustomDoc to name a few. Part two of this article explains how to retrieve a reference to the client site while processing IPersistMoniker::Load, and how to use the IServiceProvider and IOleCommandTarget interfaces to send messages between the Active document (DocObject) and its host.

IPersistMoniker and IBindCtx

When the WebBrowser Control determines that a hyperlinked resource is associated with a helper application, it creates an instance of the target application and prompts the Active document (DocObject) to load the resource by using the IPersistMoniker interface. Before the browser navigates to a document, it registers a reference to its IOleClientSite interface in the binding context using IBindCtx::RegisterObjectParam. This reference allows the DocObject to retrieve and use the client site during IPersistMoniker::Load.

The following example demonstrates how to retrieve and set the client site from the binding context:

HRESULT CDoc::Load(BOOL fFullyAvailable, IMoniker *pimkName, LPBC pibc, DWORD grfMode)
{
HRESULT hr = S_OK;
CComPtr spUnk;
CComPtr spBindCtx;

// SHDOCVW stashes the client site in the bind context.
if (pibc)
{
pibc->GetObjectParam(SZ_HTML_CLIENTSITE_OBJECTPARAM, &spUnk);
if (spUnk)
{
CComQIPtr spSite(spUnk);

if (spSite)
{
hr = SetClientSite(spSite);
}
}
}
}

IServiceProvider

The IServiceProvider interface is a generic access mechanism to locate a GUID-identified service that is provided through a control or any other object. Using IServiceProvider::QueryService, its one and only method, the caller specifies a service identifier (SID), the IID of the desired interface, and the address of the interface pointer variable that is set upon a successful return.

In many ways, IServiceProvider::QueryService functions a lot like QueryInterface. However, the more adaptable IServiceProvider mechanism allows an implementer to delegate the query to one of its member objects, or to hand off the request to a callback hierarchy that is searched for an object that can support the requested IID. The implementer need not recognize the interfaces being requested. In common usage, IServiceProvider::QueryService is used to improve the discoverability of some interfaces.

QueryService Example

For example, a call to QueryService with SID_SShellBrowser gets the nearest shell browser, such as the Microsoft Internet Explorer Web Object Control (WebOC). So, if the DocObject is hosted in the search pane, it will not mistakenly execute commands on the main browser window. SID_SShellBrowser is a WebOC-specific service; any DocObject that implements the IBrowserService interface should respond to queries for this service.

The following example demonstrates this basic scenario.

    CComPtr pSvc;
CComPtr pShb;
HRESULT hr;

hr = m_pUnk->QueryInterface(IID_IServiceProvider, &pSvc);
if (S_OK == hr && pSvc)
{
hr = pSvc->QueryService(SID_SShellBrowser, IID_IShellBrowser, &pShb);
if (hr == E_NOINTERFACE)
return;

// . . . use the interface here

pShb->Release();
}

CLSID_CMarkup

The special CLSID_CMarkup GUID is used to determine if an object is a native MSHTML markup object. No code except Internet Explorer should use this CLSID. Your QueryService or QueryInterface implementation should return E_NOINTERFACE if invoked with this GUID.

PRIVATE_GUID(CLSID_CMarkup, 0x3050F4FB, 0x98B5, 0x11CF, 0xBB, 0x82, 0x00, 0xAA, 0x00, 0xBD, 0xCE, 0x0B);
Note The MSHTML implementation uses a non-standard QueryInterface for CLSID_CMarkup to obtain an object pointer without adding a reference. In other words, the out parameter ppv does not receive an interface pointer; it contains the address of the object behind pUnknown.

IOleCommandTarget

The IOleCommandTarget interface enables objects and their containers to dispatch commands to each other. Available commands are defined by integer identifiers from a command group, which is itself identified by command group ID (also a GUID). The interface allows a caller both to query for one or more supported commands within a group and to issue a command to the object.

The WebBrowser Control uses the IOleCommandTarget interface extensively. The following sections highlight just a few of the ways that the client site can communicate with its control.

Showing a Certificate Dialog

With Internet Explorer 6 for Microsoft Windows XP Service Pack 2 (SP2) and later, you can show the Certificate dialog when the user is viewing a valid Secure Hypertext Transfer Protocol (HTTPS) site. This is the same as the user clicking the lock icon in Internet Explorer. You can use the DWebBrowserEvents2::SetSecureLockIcon event to show your own icon.

#define SHDVID_SSLSTATUS 33

IOleCommandTarget *pct;
if (SUCCEEDED(pWebBrowser2->QueryInterface(IID_IOleCommandTarget, (void **) &pct)))
{
pct->Exec(&CGID_ShellDocView, SHDVID_SSLSTATUS, 0, NULL, NULL);
pct->Release();
}

Controlling Navigation (Revisited)

If the MSHTML control is aggregated, the controlling DocObject is in a position to regulate navigation events. The fact that a document can navigate on its own implies that it will also take care of updating the navigation history.

In Internet Explorer 6 and later, the DocObject can indicate to the client site that it can navigate using CGID_DocHostCmdPriv (a privately defined command group GUID) and the DOCHOST_DOCCANNAVIGATE command. A pointer to the object that implements the IHTMLWindow2 interface is passed with the command in the VARIANTARG* parameter pvaIn. (Set pvaIn to NULL if the document cannot perform its own navigation.)

DEFINE_SHLGUID( CGID_DocHostCmdPriv, 0x000214d4, 0, 0);
#define DOCHOST_DOCCANNAVIGATE 0

// Create variant, initialize with pointer to our IUnknown
VARIANTARG var;

V_VT(&var) = VT_UNKNOWN;
V_UNKNOWN(&var) = (IUnknown*)this;

// Execute IOleCommandTarget with command group and ID
m_pCmdTarg->Exec(&CGID_DocHostCmdPriv, DOCHOST_DOCCANNAVIGATE, 0L, &amp;var, NULL);

Specifying the Zone Icon

In conjunction with CGID_Explorer, the SBCMDID_MIXEDZONE command is used to determine the zone icon and text displayed in the Internet Explorer status bar.

Active document objects hosted in Internet Explorer 6 for Windows XP SP2 or later can respond to the SBCMDID_MIXEDZONE command to determine the zone icon and text displayed in the Internet Explorer status bar. The document object should implement IOleCommandTarget, and Internet Explorer calls IOleCommandTarget::Exec with the CGID_Explorer command group.

To specify the zone icon:

  1. Define SBCMDID_MIXEDZONE.

    #define SBCMDID_MIXEDZONE 39
  2. Initialize pvaOut with VariantInit.

  3. Determine the zone you wish to specify and then set pvaOut as follows. To specify:

    • Internet, Intranet, Trusted or Untrusted zones; set pvaOut->vt to VT_UI4, and set pvaOut->ulVal to URLZONE_INTERNET, URLZONE_INTRANET, URLZONE_TRUSTED or URLZONE_UNTRUSTED respectively.
    • A mixed zone, set pvaOut->vt to VT_NULL.
    • An unknown zone, set pvaOut->vt to VT_EMPTY.

If an active document does not handle SBCMDID_MIXEDZONE, the default behavior is to show Unknown Zone in the status bar.

security note Security Alert If you cannot reliably determine your document's zone, you should not handle this command.

More Examples of Commands

The IDM_CONTEXT command (CGID_EditStateCommands command group) is used to determine if editing command should be routed to the host first. An IOleCommandTarget implementation will return S_OK to indicate that editing commands should be routed.

If the host is designed to handle editing commands, it will respond to the SID_SEditCommandTarget service identifier by providing an IOleCommandTarget interface to process editing commands as defined in the CGID_MSHTML command group.

DEFINE_GUID(CGID_MSHTML, 0xde4ba900, 0x59ca,0x11cf, 0x95, 0x92, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);

For more information on editing commands, see Introduction to MSHTML Editing and MSHTML Command Identifiers reference.

Context Menus and Extensions

The IDocHostUIHandler::ShowContextMenu method was introduced in WebBrowser Customization (Part 1). The following examples demonstrate how to use the IOleCommandTarget interface with SHDVID_GETMIMECSETMENU and SHDVID_ADDMENUEXTENSIONS (CGID_ShellDocView command group) to add and remove custom menu options from the standard Internet Explorer context menu.

The WebBrowser Control gets its context menu resources from Shdoclc.dll. That knowledge and a few #defines gives you a chance to manipulate the browser's menu. Let's say for instance that you're happy with the default menu, except for the View Source option, which you'd like to eliminate. The following code loads the WebBrowser Control shortcut menu resource from Shdoclc.dll, chooses the correct menu for the context, removes the menu item corresponding to the IDM_VIEWSOURCE command, and then displays the menu.

HRESULT CBrowserHost::ShowContextMenu(DWORD dwID,
POINT *ppt,
IUnknown *pcmdTarget,
IDispatch *pdispObject)
{
#define IDR_BROWSE_CONTEXT_MENU 24641
#define IDR_FORM_CONTEXT_MENU 24640
#define SHDVID_GETMIMECSETMENU 27
#define SHDVID_ADDMENUEXTENSIONS 53

HRESULT hr;
HINSTANCE hinstSHDOCLC;
HWND hwnd;
HMENU hMenu;
CComPtr spCT;
CComPtr spWnd;
MENUITEMINFO mii = {0};
CComVariant var, var1, var2;

hr = pcmdTarget->QueryInterface(IID_IOleCommandTarget, (void**)&spCT);
hr = pcmdTarget->QueryInterface(IID_IOleWindow, (void**)&spWnd);
hr = spWnd->GetWindow(&hwnd);

hinstSHDOCLC = LoadLibrary(TEXT("SHDOCLC.DLL"));

if (hinstSHDOCLC == NULL)
{
// Error loading module -- fail as securely as possible
return;
}

hMenu = LoadMenu(hinstSHDOCLC,
MAKEINTRESOURCE(IDR_BROWSE_CONTEXT_MENU));

hMenu = GetSubMenu(hMenu, dwID);

// Get the language submenu
hr = spCT->Exec(&CGID_ShellDocView, SHDVID_GETMIMECSETMENU, 0, NULL, &amp;var);

mii.cbSize = sizeof(mii);
mii.fMask = MIIM_SUBMENU;
mii.hSubMenu = (HMENU) var.byref;

// Add language submenu to Encoding context item
SetMenuItemInfo(hMenu, IDM_LANGUAGE, FALSE, &mii);

// Insert Shortcut Menu Extensions from registry
V_VT(&var1) = VT_INT_PTR;
V_BYREF(&var1) = hMenu;

V_VT(&var2) = VT_I4;
V_I4(&var2) = dwID;

hr = spCT->Exec(&CGID_ShellDocView, SHDVID_ADDMENUEXTENSIONS, 0, &amp;var1, &var2);

// Remove View Source
DeleteMenu(hMenu, IDM_VIEWSOURCE, MF_BYCOMMAND);

// Show shortcut menu
int iSelection = ::TrackPopupMenu(hMenu,
TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD,
ppt->x,
ppt->y,
0,
hwnd,
(RECT*)NULL);

// Send selected shortcut menu item command to shell
LRESULT lr = ::SendMessage(hwnd, WM_COMMAND, iSelection, NULL);

FreeLibrary(hinstSHDOCLC);
return S_OK;
}
security note Security Alert Using LoadLibrary incorrectly can compromise the security of your application by loading the wrong DLL. Refer to the LoadLibrary documentation for information on how to correctly load DLLs with different versions of Windows.

Appending Extensions to Your Custom Menu

In the previous example, the menu (hMenu) and menu context identifier (dwID) are passed as arguments to the IOleCommandTarget with the SHDVID_ADDMENUEXTENSIONS command. This operation inserts the registered menu extensions into the menu.

Should you choose to replace the standard menu with your own, you can still append menu extensions to your custom menu. Simply include a blank IDM_MENUEXT_PLACEHOLDER menu option in your menu definition to indicate where the custom commands are to be inserted. Menu extensions are inserted just before this placeholder. You can also add your own custom command to the standard menu by inserting the menu option before IDM_MENUEXT_PLACEHOLDER, as shown in the following example.

#define IDM_MENUEXT_PLACEHOLDER  6047

// If the placeholder is gone or was never there, then just exit
if (GetMenuState(hMenu, IDM_MENUEXT_PLACEHOLDER, MF_BYCOMMAND) != (UINT) -1)
{
InsertMenu(hMenu, // The Context Menu
IDM_MENUEXT_PLACEHOLDER, // The item to insert before
MF_BYCOMMAND|MF_STRING, // by item ID and str value
IDM_MENUEXT_FIRST__ + nExtCur, // the command ID
(LPTSTR)aOpts[nExtCur].pstrText);// The menu command text

// Remove placeholder
DeleteMenu(hMenu, IDM_MENUEXT_PLACEHOLDER, MF_BYCOMMAND);
}

The menu IDs for extensions fall between IDM_MENUEXT_FIRST__ and IDM_MENUEXT_LAST__ for a maximum of 33 custom commands.

References

The following table indicates where the identifiers described in this article are defined:

IdentifierHeader File
CGID_EditStateCommandsMshtml.h
CGID_ExplorerShlguid.h
CGID_MSHTMLMshtmhst.h
CGID_ShellDocViewShlguid.h
IDM_CONTEXTMshtmcid.h
SID_SEditCommandTargetMshtml.h
SID_SShellBrowserShlguid.h
SZ_HTML_CLIENTSITE_OBJECTPARAMMshtmhst.h

原文链接:http://msdn.microsoft.com/workshop/browser/hosting/wbcustomization.asp

精选文章

Tailscale的开源仓库ScaleTail 项目分析

Tailscale的开源仓库ScaleTail 项目分析 一、项目定位 ScaleTail 是 Tailscale 官方维护的开源仓库,地址为 github.com/tailscale-dev/ScaleTail 。它本质上不是一个传统意义上的 “库",而是一个 ...