0

每天看 svn 库变更的一个小 shell 脚本


#!/bin/bash

TODAY=/tmp/$(date +%Y%m%d)
CONTENT=$TODAY/update_content_sina.tmp

if [ ! -d $TODAY ]; then
mkdir $TODAY
fi

if [ -f $CONTENT ]; then
rm $CONTENT
fi

svn up ~/job/code//sinahouse/ >> $TODAY/svn_update_list.tmp
LIST=`cat $TODAY/svn_update_list.tmp | grep ‘.php’ | awk ‘{print $2}’`

for L in $LIST; do
svn diff -r PREV $L >> $CONTENT
done

/usr/bin/vim $CONTENT

0

清除指定squid缓存文件的脚本


用wget来清空squid缓存

可以使用以下命令来清空squid的缓存:

代码:
/usr/bin/wget -O squid.log -S –header=”ragma: no-”  url

代码:

squidclient -m PURGE -p 80 “http://you.video.sina.com.cn/index.

代码:

http://www.cdn.com/api/purge.?action=purge&host=61.55.111.111&url=http://www.md5.cn/

一款老外的程序,可以批量清除某类URL的Squid缓存,支持正则表达式。

  下载网址:http://www.wa.apana.org.au/~dean/squidpurge/

  编译:
代码:
wget http://www.wa.apana.org.au/~dean … 20040201-src.tar.gz
tar zxvf purge-20040201-src.tar.gz
cd purge
make
  清除Squid缓存示例:
  1、清除 URL 以“.mp3”结尾的缓存文件(例如 http://www.s135.com/abc.mp3、http://www.s135.com/01/a.mp3)
代码:
./purge -p localhost:80 -P 1 -se ‘\.mp3$’
  2、清除URL中包含s135.com的所有缓存:
代码:
./purge -p localhost:80 -P 1 -se ‘s135.com’
  我喜欢将程序推到后台去执行,让它慢慢地去清Squid缓存,同时将输出内容记录到purge.log文件:
代码:
./purge -p localhost:80 -P 1 -se ‘s135.com’ > purge.log 2>&1

 Squid web缓存加速软件目前已经是新浪、搜狐、网易等各大网站广泛应用。Squid会在设置的缓存目录下建立多个目录,每一个目录下又建立多个目录,然后才在最里层的目录中存放缓存文件(object)。squid会根据用户请求网页的URL进行哈希,生成缓存文件,存放在某一个目录中。squid启动之后,将在内存中建立一个哈希表,记录硬盘中缓存文件配置的情形。

  对于类似http://you.video.sina.com.cn/index.html之类的网页,squid只会生成一个缓存文件。可以用squid附带的squidclient工具清除:

代码:
squidclient -m PURGE -p 80 “http://you.video.sina.com.cn/index.html”
  而对于带有参数的网页,例如新浪播客的Flash播放器http://vhead.blog.sina.com.cn/pl … 9852&uid=1278987704,因“?”后面的参数不同,导致URL也不同,squid会生成多个缓存文件,哈希分散存放在不同的目录。如果修改了这个outer_player.swf文件,要更新squid缓存就要去清除不同目录下及内存中的很多个缓存文件,十分麻烦,于是我编写了一个Linux下的shell脚本,去完成这件麻烦的事:

  脚本文件名:clear_squid_cache.sh(8月2日修正了UC网友“城市中的寂寞”反馈的BUG)

代码:
#!/bin/sh
squidcache_path=”/data1/squid/var/cache”
squidclient_path=”/usr/local/squid/bin/squidclient”
grep -a -r $1 $squidcache_path/* | strings | grep “http:” | awk -F’http:’ ‘{print “http:”$2;}’ > cache_list.txt
for url in `cat cache_list.txt`; do
$squidclient_path -m PURGE -p 80 $url
done
  注意:请赋予clear_squid_cache.sh可执行权限(命令:chmod +x ./clear_squid_cache.sh)。请确保脚本所在目录可写。

  设置:
  squidcache_path= 表示squid缓存目录的路径
  squidclient_path= 表示squidclient程序所在的路径,默认为squid安装目录下的bin/squidclient

  用法:
  1、清除所有Flash缓存(扩展名.swf):
  
代码:
./clear_squid_cache.sh swf
  2、清除URL中包含sina.com.cn的所有缓存:
  
代码:
./clear_squid_cache.sh sina.com.cn
  3、清除文件名为zhangyan.jpg的所有缓存:
  
代码:
./clear_squid_cache.sh zhangyan.jpg
  效率:
  经测试,在DELL 2950上清除26000个缓存文件用时2分钟左右。平均每秒可清除缓存文件177个。

0

实现和IE浏览器交互的几种方法的介绍


内容
实现和IE浏览器交互的几种方法的介绍
—- 1.引言

—- 如何实现对IE浏览器中对象的操作是一个很有实际意义问题,通过和IE绑定的DLL我们可以记录IE浏览过的网页的顺序,分析用户的使用行为和模式。我们可以对网页的内容进行过滤和翻译,可以自动填写网页中经常需要用户填写的Form内容等等,我们所有的例子代码都是通过VC来表示的,采用的原理是通过和IE对象的接口的交互来实现对IE的访问。实际上是采用COM的技术,我们知道COM是和语言无关的一种二进制对象交互的模式,所以实际上我们下面所描述的内容都可以用其他的语言来实现,比如VB,DELPHI,C++ Builder等等。

—- 2.IE实例遍历实现

—- 首先我们来看系统是如何知道当前有多少个IE的实例在运行。

—- 我们知道在Windows体系结构下,一个应用程序可以通过操作系统的运行对象表来和这些应用的实例进行交互。但是IE当前的实现机制是不在运行对象表中进行注册,所以需要采用其他的方法。我们知道可以通过ShellWindows集合来代表属于shell的当前打开的窗口的集合,而IE就是属于shell的一个应用程序。

—- 下面我们描述一下用VC实现对当前 IE实例的进行遍历的方法。IShellWindows是关于系统shell的一个接口,我们可以定义一个如下的接口变量:

SHDocVw::IShellWindowsPtr m_spSHWinds;
然后创建变量的实例:
   m_spSHWinds.CreateInstance
   (__uuidof(SHDocVw::ShellWindows));
通过IShellWindows接口的方法GetCount
可以得到当前实例的数目:
      long nCount = m_spSHWinds- >GetCount();
通过IShellWindows接口的方法Item
可以得到每一个实例对象
    IDispatchPtr spDisp;
    _variant_t va(i, VT_I4);
    spDisp = m_spSHWinds->Item(va);
然后我们可以判断实例对象是不是
属于IE浏览器对象,通过下面的语句实现:
    SHDocVw::IWebBrowser2Ptr spBrowser(spDisp);
    assert(spBrowser != NULL)

—-在得到了IE浏览器对象以后,我们可以调用IWebBrowser2Ptr接口的方法来得到当前的文档对象的指针: MSHTML::IHTMLDocument2Ptr spDoc(spBrowser->GetDocument());

—- 然后我们就可以通过这个接口对这个文档对象进行操作,比如通过Gettitle得到文档的标题。

—- 我们在浏览网络的时候,一般总会同时开很多IE的实例,如果这些页面都是很好的话,我们可能想保存在硬盘上,这样,我们需要对每一个实例进行保存,而如果我们采用上面的原理,我们可以得到每一个IE的实例及其网页对象的接口,这样就可以通过一个简单的程序来批量的保存当前的所有打开的网页。采用上面介绍的方法实现了对当前IE实例的遍历,但是我们希望得到每一个IE实例所产生的事件,这就需要通过DLL的机制来实现。

—- 3.和IE相绑定的DLL的实现

—- 我们介绍一下如何建立和IE进行绑定的DLL的实现的过程。为了和IE的运行实例进行绑定,我们需要建立一个能够和每一个IE实例进行绑定的DLL。IE的启动过程是这样的,当每一个IE的实例启动的时候,它都会在注册表中去寻找这个的一个CLSID,具体的注册表的键位置为:

HKEY_LOCALL_MACHINESOFTWAREMicrosoftWindows
CurrentVersionExplorerBrowser Helper Objects

—- 当在这个键位置下存在CLSIDs的时候,IE会通过使用CoCreateInstance()方法来创建列在该键位置下的每一个对象的实例。注意对象的CLSIDs必须用子键而非启动过程是这样的,当每一个IE的实例启动的时候名字值的形式表现,比如{DD41D66E-CE4F-11D2-8DA9-00A0249EABF4} 就是一个有效的子键。我们使用DLL的形式而非EXE的形式的原因是因为DLL和IE实例运行在同一个进程空间里面。每一个这种形式的DLL必须实现接口IObjectWithSite,其中方法SetSite必须被实现。通过这个方法,我们自己的DLL就可以得到一个指向IE COM对象的IUnknown的指针,实际上通过这个指针我们就可以通过COM对象中的方法QueryInterface来遍历所有可以得到的接口,这是COM的基本的机制。当然我们需要的只是IWebBrowser2这个接口。

—- 实际上我们建立的是一个COM对象,DLL只不过是COM对象的一种表现形式。我们建立的COM对象需要建立和实现的方法有:

—-1. IOleObjectWithSite接口的方法SetSite必须实现。实际上IE实例通过这个方法向我们的COM对象传递一个接口的指针。假设我们有一个接口指针的变量,不妨设为:

—-CComQIPtr< IWebBrowser2, &IID_IWebBrowser2 > m_myWebBrowser2;

—- 我们就可以在方法SetSite中把这个传进来的接口指针赋给m_myWebBrowser2。 2. 在我们得到了指向IE COM对象的接口后,我们需要把自己的DLL和IE实例所发生的事件相关连,为了实现这个目的,需要介绍两个接口:

—-(1) IConnectionPointContainer。:

—-CComQIPtr< IWebBrowser2, &这里使用这个接口的目的是用来根据它得到的IID来建立和DLL的一个特定的连接。比如我们可以进行如下的定义:

CComQIPtr< IConnectionPointContainer,
&IID_IConnectionPointContainer >          
spCPContainer(m_myWebBrowser2);

—-然后,我们需要把所有IE中发生的事件和我们的DLL进行通讯,可以使用 IConnectPoint。

—-(2) IConnectPoint。通过这个接口,客户可以对连接的对象开始或者是终止一个advisory循环。IConnectPoint有两个主要的方法,一个为Advice,另一个为Unadvise。对于我们的应用来说,Advise是用来在每一个IE发生的事件和DLL之间建立一个通道。而Unadvise就是用来终止以前用Advise建立的通知关系。比如我们可以定义IConnectPoint接口如下: CComPtr< IConnectionPoint > spConnectionPoint;

—- 然后,我们要使所有在IE实例中发生的事件和我们的DLL相关,可以使用 如下的方法:

hr = spCPContainer->FindConnectionPoint(
DIID_DWebBrowserEvents2, &spConnectionPoint);

—-然后我们通过IConnectPoint接口的方法Advice使每当IE有一个新的事件发生的时候,都能够让我们的DLL知道。可以用如下的语句实现:

hr = spConnectionPoint- >Advise(
(IDispatch*)this, &m_dwIDCode);

—-在把IE实例中的事件和我们的DLL之间建立联系以后,我们可以通过IDispatch接口的Invoke()方法来处理所有的IE的事件。

—-3. IDispatch接口的Invoke()方法。IDispatch是从IUnknown中继承的一个接口的类型,通过COM接口提供的任何服务都可以通过IDispatch接口来实现。IDispatch::Invoke的工作方式同vtbl幕后的工作方式是类似的,Invoke将实现一组按索引来访问的函数,我们可以对Invoke方法进行动态的定制以提供不同的服务。Invoke方法的表示如下:

STDMETHOD(Invoke)(DISPID dispidMember,REFIID
riid, LCID lcid, WORD wFlags,
DISPPARAMS * pdispparams, VARIANT * pvarResult,
EXCEPINFO * pexcepinfo, UINT * puArgErr);

—-其中,DISPID是一个长整数,它标识的是一个函数。对于IDispatch的某一个特定的实现,DISPID都是唯一的。IDispatch的每一个实现都有其自己的IID,这里dispidMemeber实际上是可以认为是和IE实例所发生的每一个事件相关的方法,比如:DISPID_BEFORENAVIGATE2,DISPID_NAVIGATECOMPLETE2等等。 这个方法中另外一个比较重要的参数是DISPPARAMS,它的结构如下:

typedef struct tagDISPPARAMS
   {
       VARIANTARG* rgvarg;
//VARIANTARG是同VARAIANT相同的,可以在
    //OAIDL.IDL中找到。所以实际上rgvarg是一个参数数
     //组
       DISPID*  rgdispidNameArgs;  //命名参数的DISPID
       unsigned int cArgs;    //表示数组中元素的个数
       unsigned int CnameArgs;  //命名元素的个数
   }DISPPARAMS

—-要注意的是每一个参数的类型都是VARIANTARG,所以在IE和我们DLL之间可以传递的参数类型的数目是有限的。只有那些能够被放到VARIANTARG结构中的类型才可以通过调度接口进行传递。 比如对于事件DISPID_NAVIGATECOMPLETE2来说:第一个参数表示IE在访问的URL的值,类型是VT_BYREF|VT_VARIANT。注意DISPID_NAVIGATECOMPLETE2等DISPID已经在VC中被定义,我们可以直接进行使用。 如上说述,我们在方法Invoke中可以得到所有IE实例所发生的事件,我们可以把这些数据放到文件中进行事后的分析,也可以放到一个列表框中实时的显示。

—- 4.微软的HTML文档对象模型和应用分析

—- 下面我们来看如何得到网页文档的接口:网页文档的接口为IHTMLDocument2,可以通过调用IE COM对象的get_Document方法来得到网页的接口。使用如下的语句:

hr = m_spWebBrowser2- >get_Document(&spDisp);
CComQIPtr< IHTMLDocument2,
&IID_IHTMLDocument2 > spHTML;
spHTML = spDisp;

—- 这样我们就得到了网页对象的接口,然后我们就可以对网页进行分析,比如通过IHTMLDocument2提供的方法get_URL我们可以得到和该网页相关的URL的地址值,通过get_forms方法可以该网页中所有的Form对象的集合。实际上W3C组织已经制定了一个DOM(Document Objec Model)标准,当然这个标准不仅仅是针对HTML,同时还是针对XML制定的。W3C组织只是定义了网页对象的接口,不同的公司可以采用不同的语言和方法进行具体的实现。按照W3C组织定义的网页对象被认为是动态的,即用户可以动态的对网页对象里面所包含的每一个对象进行操作。这里的对象可以是指一个输入框,也可以是图象和声音等对象。同时按照W3C的正式文档的说明,网页对象是可以动态增加和删除的。事实上,很少有厂商实现了DOM定义的所有功能。微软对网页对象的定义也基本上是按照这个标准实现的。但是当前的接口还不支持动态的增加和删除元素,但是可以对网页中的基本元素进行属性的修改。比如IHTMLElementCollection表示网页中一些基本的元素的集合,IHTMLElement表示网页中的一个基本的元素。而象IHTMLOptionElement接口就表示一个特定的元素Option。基本的元素都有setAttribute和geAttribute方法来动态的设置和得到元素的名称和值。

—- 较为常见的一个应用是我们能够分析网页中是否有需要填写的Forms,如果这个网址的Forms以前已经填写过而且数据我们已经保存下来的话,我们就可以把数据自动放到和该URL下的Forms的相关的位置中去。另外,我们可以总结网页上需要填写的Form的数据项,先对这些数据项进行赋值,以后碰到有相同的数据项的时候就自动把我们赋值的内容填写进去。实际上Form是对象,Form中包含的元素,比如INPUT,OPTION,SELECT等类型的输入元素都是对象。

—- 另外一个可以想到的应用是自动对网页中的文本进行翻译,因为我们可以修改网页中任何对象的属性,所以我们可以把里面不属于本国语言的部分自动翻译成本国语言,当然真正的实现还要靠自然语言理解方面技术的突破,但是IE浏览器的接口和对象的形式使我们能够灵活的控制整个IE,无论是从事件对象还是到网页对象。

—- 5.小结

—- 上面我们分析了如何得到所有IE的实例,同时介绍了和IE实例相捆绑的DLL的详细的实现机制,同时对网页的对象化进行了分析。并且介绍了几个相关的应用和实现的方法及存在的技术问题。IE是一个组件化的以COM为基础的浏览器,它具有强大的功能,同时为应用开发者留下了广阔的空间,当然它也存在体积比较大,速度相对比较慢的缺点。但是它的体系结构代表了微软先进的创新的技术,因此具有强大的生命力。

01

Internet Explorer Toolbar (Deskband) Tutorial


转至http://www.codeproject.com

The Motley Fool Quote IE Toolbar

Introduction

Having recieved a number of requests for a tutorial of sorts on developing Internet Explorer Toolbars with the RBDeskband and CWindowImpl wizards that I created, I have come up with a simple sample toolbar which can be used as a reference when developing your own toolbars or explorer bars. The tutorial will walk you through the stages of developing a toolbar for that is very similar to the Address bar that is already present in . I wanted to do a tutorial that would provide a realistic sample and would produce an end result that could be used by others after the tutorial was finish. So, the tutorial is going to show you how to develop an toolbar to get stock quote information from The Motley Fool website. So with that, let us get started.

Prequisites

This tutorial assumes that you already know how to program in C++ and know some information about ATL and COM. To work through this tutorial, you will need the following installed on your development machine:

  • Visual C++6 installed
  • RBDeskBand ATL Object Wizard (Version 2.0) [get it here]
  • CWindowImpl ATL Object Wizard [get it here]

The Framework

The IE toolbar consists of a COM component supporting IDeskband and a few other necessary interfaces for which IE looks for when loading registered toolbars, explorer bars and deskbands. The RBDeskband ATL Object Wizard provides most of the framework for this article. What we will need to do is create our project, a new COM object to house our toolbar, and a few CWindowImpl classes using the CWindowImpl ATL Object Wizard. Then connecting these parts together we will produce the IE toolbar in the picture at the top of the article. Visually the toolbar consists of an editbox and a toolbar with one button on it. In actuality the toolbar consists of the fore mentioned and a non visible window that is used to reflect messages to the Toolbar window, which will process or forward messges to itself and the edit box.

Creating The

We will not work through the steps in creating the shell for our toolbar.

Creating The Project

  • If you have not done so already, start Visual C++6.
  • Then, from the File menu select New menu item; the New Dialog pops up.
  • In the New Dialog, select the Projects tab, if not already selected.
  • Select ATL COM AppWizard from the list view, if not already selected.
  • In the Project name, type "MotleyFool". See Figure 1.
  • Click the OK Button.

Figure 1. New Dialog.
Figure 1. New Dialog.
  • The ATL COM AppWizard will kick in.
  • Clicking the Finish Button, accepting the default AppWizard attributes. See Figure 2.
  • The New Project Information Dialog will present itself requesting confirmation of your project settings.
  • Click the OK Button.

Figure 2. ATL COM AppWizard
Figure 2. ATL COM AppWizard.

Creating The DeskBand Object

Now that we have our project container we need to add our IDeskBand derived component so that the DLL actually exposes something.

  • From the Insert menu, select New ATL Object menu item; the ATL Object Wizard dialog is invoked.
  • In the ATL Object Wizard dialog, select the RadBytes Category. If this category is missing then make sure that the RBDeskband and CWindowImpl ATL Object Wizards are installed.
  • Next select the DeskBand item from the Objects list.
  • Click the Next button to invoke the ATL Object Wizard Properties dialog for the Deskband object. See Figure 3.
  • On the Names property page, type "StockBar" into the Short Name field. See Figure 4.
  • Select the DeskBand ATL Object Wizard property page
  • Check the Internet Explorer Toolbar checkbox. See Figure 5.
  • Click the OK button on the ATL Object Wizard Properties Dialog. The ATL Object Wizard will create the files necessary for our DeskBand’s base implementation.

Figure 3. ATL Object Wizard.
Figure 3. ATL Object Wizard.
Figure 4. ATL Object Wizard Properties - Names.
Figure 4. ATL Object Wizard Properties – Names.
Figure 5. ATL Object Wizard Properties - DeskBand ATL Object Wizard.
Figure 5. ATL Object Wizard Properties – DeskBand ATL Object Wizard

Now our project has the DeskBand implementation that we will modify to produce the toolbar pictured at the top of the article. First we will create the window classes we will need and then come back to the Desbkand object and update it to use our window classes.

Creating The Window Classes

So back in the Framework section we said that we would need three window classes. One for the Edit Box, one for the toolbar, and one for message reflection back to the toolbar. Let us now create these window classes.

The Edit Window

We need to create a derived from the standard EDIT button window because we are going to be adding methods to our to help support functionality of the toolbar. This is one reason why we cannot use a CContainedWindow object directly.

  • From the Insert menu, select New ATL Object menu item; the ATL Object Wizard dialog is invoked.
  • In the ATL Object Wizard dialog, select the RadBytes Category. If this category is missing then make sure that the RBDeskband and CWindowImpl ATL Object Wizards are installed.
  • Next select the CWindowImpl item from the Objects list.
  • Click the Next button to invoke the ATL Object Wizard Properties dialog for the Deskband object. See Figure 3.
  • On the Names property page, type "EditQuote" into the Short Name field.
  • Select the CWindowImpl property page. See Figure 6.
  • Select the SUPERCLASS radio button from the DECLAR_WND_* group.
  • In the Window Class Name field, type "EDITQUOTE".
  • In the Original Class Name list, select the EDIT listbox item. See Figure 7.
  • Click the OK button on the ATL Object Wizard Properties Dialog. The ATL Object Wizard will create the files necessary for our CWindowImpl derived class implementation.

Figure 6. ATL Object Wizard Properties - Names.
Figure 6. ATL Object Wizard Properties – Names.
Figure 7. ATL Object Wizard Properties - Names.
Figure 7. ATL Object Wizard Properties – CWindowImpl.

The Toolbar Window

We need to create a derived class from the standard TOOLBARCLASSNAME window class because we are going to be adding methods to our class to help support functionality of the toolbar. It will also be the parent for the edit box and the window which the IE host will request from our DeskBand.

  • From the Insert menu, select New ATL Object menu item; the ATL Object Wizard dialog is invoked.
  • In the ATL Object Wizard dialog, select the RadBytes Category. If this category is missing then make sure that the RBDeskband and CWindowImpl ATL Object Wizards are installed.
  • Next select the CWindowImpl item from the Objects list.
  • Click the Next button to invoke the ATL Object Wizard Properties dialog for the Deskband object. See Figure 3.
  • On the Names property page, type "MFToolbar" into the Short Name field.
  • Select the CWindowImpl property page. See Figure 8.
  • Select the SUPERCLASS radio button from the DECLAR_WND_* group.
  • In the Window Class Name field, type "MOTLEYFOOLTOOLBAR".
  • In the Original Class Name list, select the TOOLBARCLASSNAME listbox item. See Figure 9.
  • Click the OK button on the ATL Object Wizard Properties Dialog. The ATL Object Wizard will create the files necessary for our CWindowImpl derived class implementation.

Figure 8. ATL Object Wizard Properties - Names.
Figure 8. ATL Object Wizard Properties – Names.
Figure 9. ATL Object Wizard Properties - Names.
Figure 9. ATL Object Wizard Properties – CWindowImpl.

The Reflection Window

We need to create a reflection window. It’s just a CWindowImpl window implmented class. We are going to be adding a small bit of functionality just to create the toolbar object and be able to access the toolbar member from our deskband class.

  • From the Insert menu, select New ATL Object menu item; the ATL Object Wizard dialog is invoked.
  • In the ATL Object Wizard dialog, select the RadBytes Category. If this category is missing then make sure that the RBDeskband and CWindowImpl ATL Object Wizards are installed.
  • Next select the CWindowImpl item from the Objects list.
  • Click the Next button to invoke the ATL Object Wizard Properties dialog for the Deskband object. See Figure 3.
  • On the Names property page, type "ReflectionWnd" into the Short Name field. See Figure 10.
  • We will not change any of the CWindowImpl property page values this time.
  • Click the OK button on the ATL Object Wizard Properties Dialog. The ATL Object Wizard will create the files necessary for our CWindowImpl derived class implementation.

Figure 10. ATL Object Wizard Properties - Names.
Figure 10. ATL Object Wizard Properties – Names.

Adding The Details

Now that we have our window classes available we can add our functionality for our toolbar to the appropriate window classes. Let us start with the deepest window class and work our way back out.

The EditQuote Details

For the EditQuote implementation, we need to be able to process keystrokes from the user and let the host that created our deskband object know our edit box has focus. To accomplish the first part, we need to look ahead and see that our DeskBand object will be implementing the IInputObject interface. So the host will query for that interface and know that we want to recieve messages and be given the chance to recieve focus. When the host sends our band messages to process they come through the IInputObject::TranslateAccelerator method. Our DeskBand will implement this method and it is best if our edit box, which will process the message, copy the TranslateAcceleratorIO method definition so our deskband can forward the message easily through a logical method call.

Figure 11. FileView Pane.
Figure 11. FileView Pane.

In the FileView pane (See Figure 11), double click the EditQuote.h item under Header Files. This will open the header file in the editing area. We now need to define the method definition for TranslateAcceleratorIO. To do this, add below the virtual CEditQuote destructor the following line of code:

STDMETHOD(TranslateAcceleratorIO)(LPMSG lpMsg);

Now Open the EditQuote.cpp source file and add the implementation of TranslateAcceleratorIO to the file

STDMETHODIMP CEditQuote::TranslateAcceleratorIO(LPMSG lpMsg){   TranslateMessage(lpMsg);   DispatchMessage(lpMsg);   return S_OK;}

Now our DeskBand implementation can call this message and the edit box will process the key strokes properly. But wait, our edit box should notify the toolbar to load the quote details entered if the key stroke is the enter key. For this, we will need to define a message id and send that message to the parent window to process. In the EditQuote.h header file below the include statement, add the definition of our message id as shown below in bold.

#include <commctrl.h>const int WM_GETQUOTE = WM_USER + 1024;			

In our EditQuote.cpp file we will add code to our TranslateAcceleratorIO method to process the enter key. Add the code below in bold to the EditQuote.cpp file.

STDMETHODIMP CEditQuote::TranslateAcceleratorIO(LPMSG lpMsg){   int nVirtKey = (int)(lpMsg->wParam);   if (VK_RETURN == nVirtKey)   {      // remove system beep on enter key by setting key code to 0      lpMsg->wParam = 0;      ::PostMessage(GetParent(), WM_GETQUOTE, 0, 0);      return S_OK;   }   TranslateMessage(lpMsg);   DispatchMessage(lpMsg);   return S_OK;}

Now our edit box will notify the parent when the user presses the enter key so that the parent can retrieve the requested ticker symbol details, this part will be implemented when we get to the toolbar details.

The first part of the Edit boxes implementation is finished. Now we need to be able for the edit box to have the deskband notify the host that we have focus or that we don’t have focus any longer. To do this we will need to add a method for the deskband to pass us it’s address so that we can call a method of the deskband class. These next steps will involve adding code to the CEditQuote class and to our Deskband class implementation.

Open the EditQuote.h file and add a forward reference to the CStockBar class so that we can defined our methods and members in our class header without knowing the implementation details of our deskband class, add the line in bold.

#include <commctrl.h>const int WM_GETQUOTE = WM_USER + 1024;class CStockBar;

For our class to notify the host that our deskband has focus, we need to add a message handler for EN_SETFOCUS. Add the command code handler code below in bold to your EditQuote.h file.

   BEGIN_MSG_MAP(CEditQuote)      COMMAND_CODE_HANDLER(EN_SETFOCUS, OnSetFocus)   END_MSG_MAP()

Then add the method definition for OnSetFocus to the header file below the commented out handler prototypes as follows below in bold.

// Handler prototypes:// LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);// LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);// LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled);   LRESULT OnSetFocus(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);

Before we implement the OnSetFocus method, we need to define a method for our deskband to tells of it’s address and to retain that address for later use. Add the following lines of code to your EditQuote.h file below the TranslateAcceleratorIO definition.

   void SetBand(CStockBar* pBand);private:   CStockBar* m_pBand;

Now we can move to your EditQuote.cpp source file and implement the message handler, the SetBand method, and update the TranslateAcceleratorIO method for focus change. At the top of the EditQuote.cpp file add the following includes to the include list as shown below in bold.

#include "stdafx.h"#include "EditQuote.h"#include "MotleyFool.h"#include "StockBar.h"

Now when we can use the methods of the CStockBar class in our code. Add to the end of the constructor, the initalization of m_pBand. Don’t forget the colon operator.

CEditQuote::CEditQuote(): m_pBand(NULL){}

Next we will add the SetBand implementation to our CEditQuote class. Notice that since it is not a com object we don’t call AddRef or Release on it. It’s just a pointer to the class and when it’s destroyed our CEditQuote instance will also be destroyed. We could have also done this inline in our header file.

void CEditQuote::SetBand(CStockBar* pBand){   m_pBand = pBand;}

Next we need to add our message handler for our EN_SETFOCUS message. Add the code below to the end of the EditQuote.cpp source file.

LRESULT CEditQuote::OnSetFocus(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled){   //Notify host that our band has the focus so TranslateAcceleratorIO    //messages are directed towards our band.   if (m_pBand) m_pBand->FocusChange(TRUE);   return 0;}

We have one more section of code to add to our CEditQuote implementation then we can move to our CStockBar class to define and implement the FocusChange method. Add the following code to the CEditQuote TranslateAcceleratorIO method as shown in bold. We add this code so the host knows that we are no longer needing messages.

STDMETHODIMP CEditQuote::TranslateAcceleratorIO(LPMSG lpMsg){   int nVirtKey = (int)(lpMsg->wParam);   if (VK_RETURN == nVirtKey)   {      // remove system beep on enter key by setting key code to 0      lpMsg->wParam = 0;      ::PostMessage(GetParent(), WM_GETQUOTE, 0, 0);      return S_OK;   }   else if (WM_KEYDOWN == lpMsg->message && nVirtKey == VK_TAB)   {      // we no longer need messages forwarded to our band      if (m_pBand) m_pBand->FocusChange(FALSE);      return S_FALSE;   }   TranslateMessage(lpMsg);   DispatchMessage(lpMsg);   return S_OK;}

Open the StockBar.h header file and add the definition of FocusChange to it as shown below in bold.

// IStockBarpublic:   void FocusChange(BOOL bHaveFocus);

Now open the StockBar.cpp source file and add the implementation of FocusChange to it at the bottom.

void CStockBar::FocusChange(BOOL bHaveFocus){   if (m_pSite)   {      IUnknown* pUnk = NULL;      if (SUCCEEDED(QueryInterface(IID_IUnknown, (LPVOID*)&pUnk)) && pUnk != NULL)      {         m_pSite->OnFocusChangeIS(pUnk, bHaveFocus);         pUnk->Release();         pUnk = NULL;      }   }}

We have finished off the work needed for the edit box to work properly in our toolbar. Now we need to build our toolbar up so that it has a button and contains our edit box. Then we will add the nessecities to our reflection window and update our IDeskBand to provide the correct information to our host. We are almost there. If you were to compile the project and run it, it would except that the band would look like the following in figure X.

The MFToolbar Details

For the implementation of the MFToolbar window, we need to be able to have it do the following things. It must be able to process the WM_GETQUOTE message from the EditQuote window, communicate with the browser in which the toolbar is located, create the buttons and place the child on itself, forward messages to the EditQuote child window and size itself appropriately to the users actions.

So, the first thing we should do since our toolbar is going to contain an instance of CEditQuote is include the header file for the CEditQuote class. We will do this by opening the MFToolbar.h file and inserting the include statement for the CEditQuote class as shown in bold below.

#include <commctrl.h>#include "EditQuote.h"		

Next we need to add a member to our toolbar class for the CEditQuote class. We will do this by adding a private section to the end of our class and defining a member variable as shown below in bold.

   CMFToolbar();   virtual ~CMFToolbar();private:   CEditQuote m_EditWnd;

Now that we have our member defined for our EditQuote window, we need to forward window messages to it so that keyboard inputs are processed appropriately. We do this by updating the toolbar message map to chain messages to our member as shown below in bold.

   BEGIN_MSG_MAP(CMFToolbar)      CHAIN_MSG_MAP_MEMBER(m_EditWnd)   END_MSG_MAP()

Looking forward, our deskband will need to get the EditQuote member to deterimine if it has focus and also to make it function. We could just expose the EditQuote member directly by having made it a public member instead of private, but by making it private we can expose a method that will expose our member giving us flexibility later to modify the class if the need should arise. So to expose the EditQuote member, we will add a fuction to our toolbar class to return the reference to the EditQuote member. In the toolbar header file, add the method definition and implementation below in bold to it.

   CMFToolbar();   virtual ~CMFToolbar();   inline CEditQuote& GetEditBox() {return m_EditWnd;};

Now we will create our toolbar window. Our toolbar consists of the EditQuote box and a button with an icon and text on it. To house the icon, our toolbar will need an image list handle to send to the toolbar window. So we need to add a few things to our toolbar header file before we go and implement the toolbar’s creation. The first thing we will add is the member variable for our image list. Add the line in bold below to your toolbar header file.

private:   CEditQuote m_EditWnd;   HIMAGELIST m_hImageList;

Then we will add a message handler to our toolbar’s message map and define the message handlers function definition to our header file and the follow lines of code in bold to your header file.

   BEGIN_MSG_MAP(CMFToolbar)      CHAIN_MSG_MAP_MEMBER(m_EditWnd)      MESSAGE_HANDLER(WM_CREATE, OnCreate)   END_MSG_MAP()// Handler prototypes://  LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);//  LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);//  LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled);   LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);

Before we can implement our toolbar’s creation, we need to create a icon resource that our toolbar button will use next to its text. So go to the resource view and add a new icon to the project resources. You can do this by right clicking on "MotleyFool resources" and selecting "Insert…" from the context menu. In the Insert Resource dialog box, select Icon from the Resource type list and click the New button. This will insert a blank icon resource into your project. Rename the icon’s resource ID by right clicking on the icon resource in the resource view and selecting the properties menu item from the context menu. Change the id to IDI_MOTLEY. Then draw or graciously borrow an icon from The Motley Fool to use on the toolbar. I graciously borrowed the icon from their website and adapted it into the icon.

Now we can implement it our toolbars creation. Open the MFToolbar source file and implement the details of the toolbar creation as described below.

First we need to include the project resource file so we can use the icon ID in our code. Add the line in bold below to our toolbar’s source file as shown.

#include "stdafx.h"#include "resource.h"#include "MFToolbar.h"

Next we need to update our constructor implementation. We need to initialize our handle to the image list by setting it to NULL. Don’t forget the colon.

CMFToolbar::CMFToolbar(): m_hImageList(NULL){}

Next we need to update our destructor, it should destroy the image list and destroy the window if it has not yet been destroyed.

CMFToolbar::~CMFToolbar(){   ImageList_Destroy(m_hImageList);   if (IsWindow()) DestroyWindow();}

Before we can implement our toolbar’s creation, we need to add a resource symbol to our project for the toolbar button’s ID. We could just use a #define statement at the top of the source file, but for cleanliness and since we are already including the resource.h file, we will add it to our resource file. Go to the "View" menu and select "Resource Symbols" menu item. Click the "New" button on the Resource Symbols dialog. Then enter a name of "IDM_GETQUOTE" and click OK. Then close the Resource Symbols dialog.

Now we can create our toolbar, we defined the OnCreate method in our header file and need to now implement it. Add the following function and its implementation to the end of the toolbar source file.

Collapse
LRESULT CMFToolbar::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled){   // buttons with images and text   SendMessage(m_hWnd, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);   // Sets the size of the TBBUTTON structure.   SendMessage(m_hWnd, TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON), 0);   // Set the maximum number of text rows and bitmap size.   SendMessage(m_hWnd, TB_SETMAXTEXTROWS, 1, 0L);   // add our button's caption to the toolbar window   TCHAR* pCaption = _T("Get Quote");   int iIndex = ::SendMessage(m_hWnd, TB_ADDSTRING, 0,(LPARAM)pCaption);   // load our button's icon and create the image list to house it.   HICON hMotley = LoadIcon(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDI_MOTLEY));   m_hImageList = ImageList_Create(16,16, ILC_COLOR16, 1, 0);   int iImageIndex = ImageList_AddIcon(m_hImageList, hMotley);   DestroyIcon(hMotley);   // Set the toolbar's image   ::SendMessage(m_hWnd, TB_SETIMAGELIST, 0, (LPARAM)m_hImageList);   // add the button for the toolbar to the window   TBBUTTON Button;   ZeroMemory((void*)&Button, sizeof(TBBUTTON));   Button.idCommand = IDM_GETQUOTE;   Button.fsState = TBSTATE_ENABLED;   Button.fsStyle = BTNS_BUTTON | BTNS_AUTOSIZE | BTNS_SHOWTEXT;   Button.dwData = 0;   Button.iString = iIndex;   Button.iBitmap = 0;   ::SendMessage(m_hWnd, TB_INSERTBUTTON, 0, (LPARAM)&Button);   // create our EditQuote window and set the font.   RECT rect = {0,0,0,0};   m_EditWnd.Create(m_hWnd, rect, NULL, WS_CHILD|WS_VISIBLE, WS_EX_CLIENTEDGE);   m_EditWnd.SetFont(static_cast<HFONT>(GetStockObject(DEFAULT_GUI_FONT)));   return 0;}

If you try to compile at this point, you will see that there are unresolved externals for the image list method calls. We need to add a library to the project. To do this select the "Project|Settings" menu item. On the Project Settings dialog, Select All Configurations from the "Settings For" combo box. Then select the "Link" tab and append to the "Object/Library modules" edit box "comctl32.lib". Then click OK. If you compile the project now, it will compile successfully and the image list unresolved externals will disappear.

We still have a few things we need to do to the Toolbar window. It needs to process Command messages, resopnd to WM_GETQUOTE messages, and resize itself. Let’s conquer the latter first.

To orgainze the tooblar correctly, we should have the toolbar responsd to WM_SIZE messages. To do this, we will add to our tooblar header file a message handler for the WM_SIZE message and add a function definition for OnSize which WM_SIZE messages will be sent to. Open our toolbar header file and add the lines in bold below to it as shown.

   BEGIN_MSG_MAP(CMFToolbar)      CHAIN_MSG_MAP_MEMBER(m_EditWnd)      MESSAGE_HANDLER(WM_CREATE, OnCreate)      MESSAGE_HANDLER(WM_SIZE, OnSize)   END_MSG_MAP()// Handler prototypes://  LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);//  LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);//  LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled);   LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);   LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);

Now we need to implement our OnSize function. Open the toolbar source file and add the function implementation below to the end of the file.

Collapse
LRESULT CMFToolbar::OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled){   // based on the size of the window area minus the size of the toolbar button,    // indent the toolbar so that we can place the edit box before the toolbar    // button. This will right justify the toolbar button in the toolbar and the    // edit box will use the vaction space to the left of the button but after the    // toolbar text as it's usable space.   RECT wndRect, btnRect;   GetClientRect(&wndRect);   ::SendMessage(m_hWnd, TB_GETITEMRECT, 0, (LPARAM)&btnRect);   wndRect.right -= (btnRect.right - btnRect.left);   SendMessage(TB_SETINDENT, wndRect.right - wndRect.left);   // put a small spacing gap between the edit box's right edge and the toolbar button's left edge   wndRect.right -= 3;   m_EditWnd.MoveWindow(&wndRect, FALSE);   return 0;}

We still need to respond to user input for the toolbar button and from the edit box when the user presses the enter key. What we want the toolbar to do is tell the web browser host to navigate to the motely fool website and retrieve the stock quotes requested. First we need for the Deskband object to tell our toolbar window what the web browser instance is so that the toolbar window can communicate with it. To do this, we will add a private member variable and a public method in which the deskband can set the web browser instance. Our window will then use the member variable set to tell the web browser where to navigate and what to retrieve.

To do this, open the toolbar header file and add the lines in bold to the file.

   CMFToolbar();   virtual ~CMFToolbar();   inline CEditQuote& GetEditBox() {return m_EditWnd;};   void SetBrowser(IWebBrowser2* pBrowser);private:   CEditQuote m_EditWnd;   HIMAGELIST m_hImageList;   IWebBrowser2* m_pBrowser;

Now, open the toolbar source file. We will update the constructor and initialize our member variable to null. Then we will update the toolbar destructor and release the member variable if it hasn’t been. Then we will implement the SetBrowser method.

Initialize the web browser member variable.

CMFToolbar::CMFToolbar(): m_hImageList(NULL), m_pBrowser(NULL){}

Release the web browser object if held.

CMFToolbar::~CMFToolbar(){   ImageList_Destroy(m_hImageList);   SetBrowser(NULL);   if (IsWindow()) DestroyWindow();}

Implement SetBrowser()

void CMFToolbar::SetBrowser(IWebBrowser2* pBrowser){   if (m_pBrowser) m_pBrowser->Release();   m_pBrowser = pBrowser;   if (m_pBrowser) m_pBrowser->AddRef();}

If you try and compile the project, you will notice that IWebBrowser2 is undefine in our header file. This is because we need to update our stdafx.h header file to include system files that define IWebBrowser2. To do this, open stdafx.h and add the following lines in bold to the file, then recompile.

extern CComModule _Module;#include <atlcom.h>#include <atlwin.h>//// These are needed for IDeskBand//#include <shlguid.h>#include <shlobj.h>

Now we can add message handlers for WM_COMMAND and WM_GETQUOTE to our toolbar class to handle the toolbar button being pressed and the enter key being pressed in the edit box by the user. To do this, we will need to add to our toolbar header file message handlers and function definitions for WM_COMMAND and WM_GETQUOTE. We will also need to add a private method which both will call if they need to to preform the same functionality (better than repeating code that does the same thing). So let’s add the message handlers to the header file.

Collapse
   BEGIN_MSG_MAP(CMFToolbar)      CHAIN_MSG_MAP_MEMBER(m_EditWnd)      MESSAGE_HANDLER(WM_CREATE, OnCreate)      MESSAGE_HANDLER(WM_SIZE, OnSize)      MESSAGE_HANDLER(WM_COMMAND, OnCommand)      MESSAGE_HANDLER(WM_GETQUOTE, OnGetQuote)   END_MSG_MAP()// Handler prototypes://  LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);//  LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);//  LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled);   LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);   LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);   LRESULT OnCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);   LRESULT OnGetQuote(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);

Now we can add the function delcaration for our GetQuote privaet method.

private:   CEditQuote m_EditWnd;   HIMAGELIST m_hImageList;   IWebBrowser2* m_pBrowser;   void GetQuote();

Now let’s switch to our source file and implement our message handler functions and the GetQuote method. Add the code below to the end of the toolbar source file.

Collapse
LRESULT CMFToolbar::OnCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled){   if (!HIWORD(wParam))   {      long lSite = LOWORD(wParam);      if ( lSite == IDM_GETQUOTE)      {         GetQuote();         return 0;      }   }   return -1;}LRESULT CMFToolbar::OnGetQuote(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled){   GetQuote();   return 0;}void CMFToolbar::GetQuote(){   // if we have a web browser pointer then try to navigate to The Motley Fool site to retrieve stock quotes.   if (m_pBrowser)   {      VARIANT vEmpty;      VariantInit(&vEmpty);      m_pBrowser->Stop();      _bstr_t bsSite;      // if the user has entered stock quotes then append them to the url      if (m_EditWnd.GetWindowTextLength())      {         BSTR bstrTickers = NULL;         m_EditWnd.GetWindowText(&bstrTickers);         bsSite = "http://quote.fool.com/news/symbolnews.asp?Symbols=";         bsSite += bstrTickers;         SysFreeString(bstrTickers);      }      // if the user has not entered any stock quotes then just take them to The Motley Fool website.      else         bsSite = "http://www.fool.com";      // have the webrowser navigate to the site URL requested depending on user input.      m_pBrowser->Navigate(bsSite, &vEmpty, &vEmpty, &vEmpty, &vEmpty);   }}

If you try to compile, you will notice that _bstr_t is undefined. That is because the class is defined in comdef.h. We need to add this to our stdafx.h header file so that we can use it as well as any other class in our project (which we will need to for IInputObject). Open the stdafx.h header file and add the lines in bold to the file as indicated.

#include <shlobj.h>// needed for IInputObject and _bstr_t#include <comdef.h>

Our implementation of the toolbar window is complete. Now we can move on to the Reflection window which creates our toolbars and forwards command messages to it.

The Reflection Window Details

For the Reflection Window, it’s only purpose is to create the toolbar window (which it doesn’t need to really do, but by doing so eases message forwarding) and forward messages to it. The reflection window is not visible, it’s just a layer added so that message from the toolbar get to the toolbar. If we didn’t have this window present, toolbar messages would get sent to the parent window (which we do not control) and we would never get them. This is not good since we need to respond to WM_COMMAND messages from the toolbar. Thus the need for the reflection window. So let’s create the toolbar window and the message forwarding for it.

Open the ReflectionWnd.h header file. We will need to include the toolbar header file and add a private member variable to our reflection window to create it and to pass it to the message chain. First things first, add the include statement below so we can use the CMFToolbar class.

#include <commctrl.h>#include "MFToolbar.h"

Next add a private member variable to the end of the reflection window class for the toolbar as shown below.

	CReflectionWnd();   virtual ~CReflectionWnd();private:   CMFToolbar m_ToolbarWnd;

Next update the reflection window message map to forward messages to the toolbar window as shown below.

   BEGIN_MSG_MAP(CReflectionWnd)      CHAIN_MSG_MAP_MEMBER(m_ToolbarWnd)   END_MSG_MAP()

We will also need a public function for our deskband class to get at our toolbar window. We will do the same as we did with the EditQuote window by providing a function to get at the member variable indirectly. Add the line of code in bold below to the header file as indicated.

   CReflectionWnd();   virtual ~CReflectionWnd();   inline CMFToolbar& GetToolBar() { return m_ToolbarWnd;};

Lastly, we need to create the toolbar window and will do so in the WM_CREATE message handler for our reflection window. Add the code below in bold to the reflection window header file. Then we will implement the OnCreate method in the source file.

   BEGIN_MSG_MAP(CReflectionWnd)      MESSAGE_HANDLER(WM_CREATE, OnCreate)      CHAIN_MSG_MAP_MEMBER(m_ToolbarWnd)   END_MSG_MAP()// Handler prototypes://  LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);//  LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled);//  LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled);   LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);

Now open the ReflectionWnd.cpp source file and add the implementation of OnCreate to its end.

const DWORD DEFAULT_TOOLBAR_STYLE =       /*Window styles:*/ WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE | WS_TABSTOP |      /*Toolbar styles:*/ TBSTYLE_TOOLTIPS | TBSTYLE_FLAT | TBSTYLE_TRANSPARENT | TBSTYLE_LIST | TBSTYLE_CUSTOMERASE |                          TBSTYLE_WRAPABLE |      /*Common Control styles:*/ CCS_TOP | CCS_NODIVIDER | CCS_NOPARENTALIGN | CCS_NORESIZE;LRESULT CReflectionWnd::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled){   RECT rect;   GetClientRect(&rect);   m_ToolbarWnd.Create(m_hWnd, rect, NULL, DEFAULT_TOOLBAR_STYLE);   return 0;}

You will notice that we defined a constant for the toolbar style. This was done to make the code more readable.

The only thing left to do to the reflection window code is update the destructor to destory the window if it’s still present.

CReflectionWnd::~CReflectionWnd(){   if (IsWindow()) DestroyWindow();}

 

Finishing Off The Deskband Toolbar

All that’s left is for our deskband to create the toolbar window, have the host use the toolbar window, remove the unused IPersistStream implementation, implement IInputObject (for focus control) and do some code tweaking. So lets wrap this toolbar up. Open the StockBar.h header file. Remove the following lines of code that are in bold since we moved them to our stdafx.h for our other classes to also use.

#include "resource.h"       // main symbols//// These are needed for IDeskBand//#include <shlguid.h>#include <shlobj.h>

Next remove the following line from the class delcaration.

public IPersistStream,

The top of the class declaration should now look like this,

class ATL_NO_VTABLE CStockBar :    public CComObjectRootEx<CComSingleThreadModel>,   public CComCoClass<CStockBar, &CLSID_StockBar>,   public IDeskBand,   public IObjectWithSite,   public IDispatchImpl<IStockBar, &IID_IStockBar, &LIBID_MOTLEYFOOLLib>{

Next scroll down to the COM Map and remove the following two lines of code,

   COM_INTERFACE_ENTRY(IPersist)   COM_INTERFACE_ENTRY(IPersistStream)

Your COM Map should now look like this,

BEGIN_COM_MAP(CStockBar)   COM_INTERFACE_ENTRY(IStockBar)   COM_INTERFACE_ENTRY(IOleWindow)   COM_INTERFACE_ENTRY_IID(IID_IDockingWindow, IDockingWindow)   COM_INTERFACE_ENTRY(IObjectWithSite)   COM_INTERFACE_ENTRY_IID(IID_IDeskBand, IDeskBand)   COM_INTERFACE_ENTRY(IDispatch)END_COM_MAP()

Scroll down the header file further and remove the sections of function declarations for IPersist and IPersistStream, which includes the following lines.

// IPersistpublic:   STDMETHOD(GetClassID)(CLSID *pClassID);// IPersistStreampublic:   STDMETHOD(IsDirty)(void);   STDMETHOD(Load)(IStream *pStm);   STDMETHOD(Save)(IStream *pStm, BOOL fClearDirty);   STDMETHOD(GetSizeMax)(ULARGE_INTEGER *pcbSize);

There should now be nothing related to IPersist or IPersistStream between the IDockingWindow and IStockBar function declaration sections.

Now we need to remove the IPersist and IPersistStream function implementations from the StockBar.cpp source file. Find the GetClassID, IsDirty, Load, Save, and GetSizeMax function implementations and remove them from the file. They should be directly above the FocusChange Method we added earlier.

Now we can start adding code to our deskband. Open the stockbar.h header file and add the include for the reflection window class as shown below in bold.

#include "resource.h"       // main symbols#include "ReflectionWnd.h"

Next, find the protected section at the end of the file and replace the line

   HWND m_hWnd;

with

   CReflectionWnd m_ReflectWnd;

If you try to compile, you will find that it will be unsuccessful since we have removed m_hWnd and have not removed all occurances of m_hWnd from the class source file. We will replace all occurances with more appropriate code for our Reflection window and toolbar window. Open the StockBar.cpp source file, Remove the following line from the class constructor

   m_hWnd(NULL),

your class constructor should now look as follows with a SetBand call added,

CStockBar::CStockBar():    m_dwBandID(0),    m_dwViewMode(0),    m_bShow(FALSE),    m_bEnterHelpMode(FALSE),    m_hWndParent(NULL),    m_pSite(NULL){	m_ReflectWnd.GetToolBar().GetEditBox().SetBand(this);}

Next, update the RegisterAndCreateWindow function by replacing the temporary m_hWnd construction with the Reflection Window construction. Your RegisterAndCreateWindow implementation should look as follows:

BOOL CStockBar::RegisterAndCreateWindow(){   RECT rect;   ::GetClientRect(m_hWndParent, &rect);   m_ReflectWnd.Create(m_hWndParent, rect, NULL, WS_CHILD);   // The toolbar is the window that the host will be using so it is the window that is important.   return m_ReflectWnd.GetToolBar().IsWindow();}

As we scroll through the code, we should fix some other things. A toolbar has a default height of 22 so we need to update our GetBandInfo method so that all the y measurements are 22 not 20. We also want our Integral sizing to be non sizeable so we need to set the DBIM_INTEGRAL x and y values to 0. While we are at it, we should fix the title of our toolbar so it says "The Motley Fool". You’ll find this constant defined near the top of the source file, update it now.

We will now update the GetWindow call so that the toolbar window handle is returned and not the invalid m_hWnd variable. Update your GetWindow method so it looks as follows,

STDMETHODIMP CStockBar::GetWindow(HWND* phwnd){   HRESULT hr = S_OK;   if (NULL == phwnd)   {      hr = E_INVALIDARG;   }   else   {      *phwnd = m_ReflectWnd.GetToolBar().m_hWnd;   }   return hr;}

Now we need to update teh CloseDW method so that it does not destory our window buy hide it. We do this much like the MFC CToolbar class does, the class destructor will destroy the window. Your CloseDW method should look as follows,

STDMETHODIMP CStockBar::CloseDW(unsigned long dwReserved){   ShowDW(FALSE);   return S_OK;}

Working our way through our class implementation, we will update the next method that needs updating. Update the ShowDW class to show or hide the toolbar window which the host is using. Your ShowDW class should look as follows,

STDMETHODIMP CStockBar::ShowDW(BOOL fShow){   m_bShow = fShow;   m_ReflectWnd.GetToolBar().ShowWindow(m_bShow ? SW_SHOW : SW_HIDE);   return S_OK;}

We are almost done modifying the CStockBar class we need to do one last bit of updating. We need to modify the SetSite implementation to release the browser window that the toolbar may be using if we have a IInputObjectSite object and we need to query the OleCommandTarget’s ServiceProvider for the IWebBrowser2 interface which we will then set to our toolbar. The modified parts of the SetSite method implementation are below in bold.

Collapse
STDMETHODIMP CStockBar::SetSite(IUnknown* pUnkSite){//If a site is being held, release it.   if(m_pSite)   {      m_ReflectWnd.GetToolBar().SetBrowser(NULL);      m_pSite->Release();      m_pSite = NULL;   }   //If punkSite is not NULL, a new site is being set.   if(pUnkSite)   {      //Get the parent window.      IOleWindow  *pOleWindow = NULL;      m_hWndParent = NULL;      if(SUCCEEDED(pUnkSite->QueryInterface(IID_IOleWindow, (LPVOID*)&pOleWindow)))      {         pOleWindow->GetWindow(&m_hWndParent);         pOleWindow->Release();      }      if(!::IsWindow(m_hWndParent))         return E_FAIL;      if(!RegisterAndCreateWindow())         return E_FAIL;      //Get and keep the IInputObjectSite pointer.      if(FAILED(pUnkSite->QueryInterface(IID_IInputObjectSite, (LPVOID*)&m_pSite)))      {         return E_FAIL;      }        IWebBrowser2* s_pFrameWB = NULL;      IOleCommandTarget* pCmdTarget = NULL;      HRESULT hr = pUnkSite->QueryInterface(IID_IOleCommandTarget, (LPVOID*)&pCmdTarget);      if (SUCCEEDED(hr))      {         IServiceProvider* pSP;         hr = pCmdTarget->QueryInterface(IID_IServiceProvider, (LPVOID*)&pSP);         pCmdTarget->Release();         if (SUCCEEDED(hr))         {            hr = pSP->QueryService(SID_SWebBrowserApp, IID_IWebBrowser2, (LPVOID*)&s_pFrameWB);            pSP->Release();            _ASSERT(s_pFrameWB);            m_ReflectWnd.GetToolBar().SetBrowser(s_pFrameWB);            s_pFrameWB->Release();         }      }   }   return S_OK;}

If you try to compile and use the toolbar right now, it will function partially. Tabbing and input control will not work correctly since we have yet to implement IInputObject for our deskband. Let’s do that now since it’s the last bit of code we will write for our simple deskband. You may also notice that the Toolbars context menu and View|Toolbars menus still say CStockBar Class. we will fix this problem in the Finishing Touches section below.

IInputObject Implementation

To get tabbing and input control to work correctly for any deskband is quite simple. You need but to implement IInputObject. The host will query our deskband to see if this interface is implemented and if it is will call the methods to see if we require input focus and let us also process messages from the user through the host. To do this, open the stockbar.h header file. To the stockbar class declaration add the line below in bold,

class ATL_NO_VTABLE CStockBar :    public CComObjectRootEx<CComSingleThreadModel>,   public CComCoClass<CStockBar, &CLSID_StockBar>,   public IDeskBand,   public IObjectWithSite,   public IInputObject,    public IDispatchImpl<IStockBar, &IID_IStockBar, &LIBID_MOTLEYFOOLLib>{

Next scroll down to the COM Map and add an entry for IInputObject as shown below in bold,

BEGIN_COM_MAP(CStockBar)   COM_INTERFACE_ENTRY(IStockBar)   COM_INTERFACE_ENTRY(IInputObject)   COM_INTERFACE_ENTRY(IOleWindow)   COM_INTERFACE_ENTRY_IID(IID_IDockingWindow, IDockingWindow)   COM_INTERFACE_ENTRY(IObjectWithSite)   COM_INTERFACE_ENTRY_IID(IID_IDeskBand, IDeskBand)   COM_INTERFACE_ENTRY(IDispatch)END_COM_MAP()

Next add the following section of function declarations to your header file, I placed mine before the IStockBar section.

// IInputObjectpublic:   STDMETHOD(HasFocusIO)(void);   STDMETHOD(TranslateAcceleratorIO)(LPMSG lpMsg);   STDMETHOD(UIActivateIO)(BOOL fActivate, LPMSG lpMsg);

All that remains is to implement these three functions. Add the function implementations below to the end of the stockbar.cpp source file.

Collapse
STDMETHODIMP CStockBar::HasFocusIO(void){   // if any of the windows in our toolbar have focus then return S_OK else S_FALSE.   if (m_ReflectWnd.GetToolBar().m_hWnd == ::GetFocus())      return S_OK;   if (m_ReflectWnd.GetToolBar().GetEditBox().m_hWnd == ::GetFocus())     return S_OK;   return S_FALSE;}STDMETHODIMP CStockBar::TranslateAcceleratorIO(LPMSG lpMsg){   // the only window that needs to translate messages is our edit box so forward them.   return m_ReflectWnd.GetToolBar().GetEditBox().TranslateAcceleratorIO(lpMsg);}STDMETHODIMP CStockBar::UIActivateIO(BOOL fActivate, LPMSG lpMsg){   // if our deskband is being activated then set focus to the edit box.   if(fActivate)   {      m_ReflectWnd.GetToolBar().GetEditBox().SetFocus();   }   return S_OK;}

Our toolbar is functionaly done, compile, run it and see. It works as described and is fairly simple. Let’s put some finishing UI touches on it for IE and our users to use.

Finishing Touches

The are only 2 finishing touches to make, One is to fix the context menu text. The other is to add button support to the main IE toolbar. Let’s do them in order.

To fix the context menu text problem, open the StockBar.rgs project file and change all occurances of "StockBar Class" to "The Motley Fool Quotes". Compile it, run it, and see. While you only need to change one of them, it’s nicer if they all match.

Now let’s add button support for our toolbar. Update the stockbar.rgs file contents by appending the text below to it’s contents.

Collapse
HKLM{   Software   {      Microsoft      {         'Internet Explorer'         {            Extensions            {               ForceRemove	{A26ABCF0-1C8F-46e7-A67C-0489DC21B9CC} = s 'The Motley Fool Quotes'               {                  val BandClsid = s '{A6790AA5-C6C7-4BCF-A46D-0FDAC4EA90EB}'                  val ButtonText = s 'The Motley Fool'                  val Clsid = s '{E0DD6CAB-2D10-11D2-8F1A-0000F87ABD16}'                  val 'Default Visible' = s 'Yes'                  val 'Hot Icon' = s '%MODULE%,425'                  val Icon = s '%MODULE%,425'                  val MenuStatusBar = s 'The Motley Fool Stock Quote Toolbar'                  val MenuText = s 'The Motley Fool'               }            }         }      }   }}

The replace the 425 with the id from resource.h of IDI_MOTLEY. Also replace the BandClsid value with the GUID of our toolbar, the above values represent the source code for the article. Now compile the toolbar again. Then start IE and right click on the Standard Buttons toolbar, Select "Customize" from the context menu. Scroll down the Available toolbar buttons listbox and find "The Motley Fool" item, See Figure 12. Select it and click the Add button in the middle of the dialog. The item will move to the right as in Figure 13. Click the Close Button. You’ll see the button added as shown in the before figure 14 and after figure 15.

Figure 12. Customize Toolbar - Available Toolbar Buttons.
Figure 12. CustomizeToolbar – Available Toolbar Buttons.
Figure 13. Customize Toolbar - Current Toolbar Buttons.
Figure 13. Customize Toolbar – Current Toolbar Buttons.
Figure 14. IE Standard Buttons - Before.
Figure 14. IE Standard Buttons – Before.
Figure 15. IE Standard Buttons - After.
Figure 15. IE Standard Buttons – After.

Conclusion

While this tutorial is long hopefully the explaination was clear. From writing this tutorial it is easy to see that the RBDeskband ATL Object Wizard has some room for improvement but provided enough of a base for us to develop our simple example. In the end you can see that the toolbar we created is much like the Address bar. The differences lie in how MS implemented theirs versus how I implemented mine. As always feedback is welcome. Enjoy.


About Erik Thompson

Site Builder

Erik lives in Redmond, Washington. He works as a Senior Software Engineer specializing in C++, COM, ATL and the middle-tier and now .NET. When he isn’t coding for work, he can be found trying to extend Internet Explorer with yet another Desk band or simplifying his development process with ATL Object Wizards.

He spends his free time snowboarding, mountain biking, reading, dining out at those hidden finds.

Click here to view Erik Thompson’s online profile.

Other popular ATL articles:

0

Shell编程 – 傻瓜教程2


 本文例子代码下载(19K)(codeproject.com)

    在这篇指南的第一部分,我给了大家一个编写外壳扩展的介绍,并且演示了一个一次操作一个简单文件的上下文菜单扩展。在第二部分中,我将要演示如何在一个操作中操作多个文件。这个扩展是一个注册和卸载COM服务器的实用工具。它还演示了如何使用ATL对话框类CDialogImpl。我将通过解释一些特殊的注册表键来讲第二部分,通过这些键你可以使你的扩展被任何文件调用,而不是那些预先选择的类型(.TXT)。

    第二部分假设你已经阅读了第一部分,所以你知道了上下文菜单扩展的基本知识。除此之外,你还必须理解COM,ATL和STL的基本知识。

上下文菜单扩展的开始-它能做什么?

    这个外壳扩展将使你注册和卸载那些在EXE,DLL和OCX里的COM服务器。不像我们在第一部分所做的那样,这个扩展将对所有你右键点击事件发生时所有选中的文件进行操作。

使用AppWizard 开始

运行AppWizard ,做一个新的ATL COM wizard app。我们叫它DllReg。在向导中保持所有默认选项,单击完成。我们现在就有了一个空的将会生成DLLATL项目,但是我们必须添加自己的外壳扩展COM对象。在ClassView树中,右键单击 DllReg classes项,选择New ATL Object

ATL Object 向导,第一面板已经选择了Simple Object ,只要单击下一步就行了。在第二面板中,在Short Name 编辑控件中输入DllRegShlExt ,然后单击确定(面板中的其它的编辑框将会自动完成)。这就创建了一个类名为CDllRegShlExt 的类,它包含了实现一个COM对象的基本代码。我们将向这个类添加我们的代码。

初始化接口

    在这个扩展中,我们的IShellExtInit::Initialize()实现将会相当不同。有两个原因,第一我们将列举所有选中的文件;第二,我们将测试我们选中的文件是否有注册(register)和卸载(unregister)函数的出口。我们将仅仅考虑那些同时有DllRegisterServer()DllUnregisterServer()出口的文件。其他的都将被忽略掉。

    我们将使用列表控件和STL的字符串与列表类,所以你必须首先在stdafx.h 文件中添加如下行:

#include <commctrl.h>#include <string>#include <list>#include <atlwin.h>typedef std::list<std::basic_string<TCHAR> > string_list;

    我们的CDllRegShlExt类也将需要一些成员变量:

protected:    HBITMAP     m_hRegBmp;    HBITMAP     m_hUnregBmp;    string_list m_lsFiles;    TCHAR       m_szDir[MAX_PATH];

    CDllRegShlExt的构造函数中将加载两幅上下文菜单中使用的位图:

CDLLRegShlExt::CDLLRegShlExt(){    m_hRegBmp = LoadBitmap ( _Module.GetModuleInstance(),                             MAKEINTRESOURCE(IDB_REGISTERBMP) );    m_hUnregBmp = LoadBitmap ( _Module.GetModuleInstance(),                               MAKEINTRESOURCE(IDB_UNREGISTERBMP) );}

    在你将IShellExtInit添加到了被CDllRegShlExt实现的接口列表中之后(关于这个操作请参见第一部分),我们开始写Initialize()函数。

  Initialize()将执行如下步骤:

  1. 改变当前目录为在资源浏览器窗口中正在被查看的目录;
  2. 列举所有被选中的文件;
  3. 对每一个文件,试图使用LoadLibrary()加载它;
  4. 如果LoadLibrary()成功,看该文件是否有DllRegisterServer()DllUnregisterServer()的函数出口;
  5. 如果两个出口都被找到了,添加该文件的的文件名到我们能操作的文件列表中,m_lsFiles
HRESULT CDllRegShlExt::Initialize (     LPCITEMIDLIST pidlFolder,    LPDATAOBJECT pDataObj,    HKEY hProgID ){TCHAR     szFile    [MAX_PATH];TCHAR     szFolder  [MAX_PATH];TCHAR     szCurrDir [MAX_PATH];TCHAR*    pszLastBackslash;UINT      uNumFiles;HDROP     hdrop;FORMATETC etc = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };STGMEDIUM stg = { TYMED_HGLOBAL };HINSTANCE hinst;bool      bChangedDir = false;HRESULT (STDAPICALLTYPE* pfn)();

    非常多的局部变量!第一步是从传进去的pDataObj参数中获得一个HDROP。这和第一部分的扩展有些相似。

    // Read the list of folders from the data object.  They're stored in HDROP    // format, so just get the HDROP handle and then use the drag 'n' drop APIs    // on it.    if ( FAILED( pDO->GetData ( &etc, &stg )))        return E_INVALIDARG;    // Get an HDROP handle.    hdrop = (HDROP) GlobalLock ( stg.hGlobal );    if ( NULL == hdrop )        {        ReleaseStgMedium ( &stg );        return E_INVALIDARG;        }    // Determine how many files are involved in this operation.    uNumFiles = DragQueryFile ( hdrop, 0xFFFFFFFF, NULL, 0 );

    接下来要做的就是一个获取下一个文件名的for循环(使用DragQueryFile())并试图用LoadLibrary()装载它。在该文的实际例子工程当中预先做了一些目录改变的工作。在这儿我把它忽略了,因为它有点儿太长了。

    for ( UINT uFile = 0; uFile < uNumFiles; uFile++ )        {        // Get the next filename.        if ( 0 == DragQueryFile ( hdrop, uFile, szFile, MAX_PATH ))            continue;        // Try & load the DLL.        hinst = LoadLibrary ( szFile );                if ( NULL == hinst )            continue;

    下一步,我们将看看它是否有两个必要函数的出口。

        // Get the address of DllRegisterServer();        (FARPROC&) pfn = GetProcAddress ( hinst, "DllRegisterServer" );        // If it wasn't found, skip the file.        if ( NULL == pfn )            {            FreeLibrary ( hinst );            continue;            }        // Get the address of DllUnregisterServer();        (FARPROC&) pfn = GetProcAddress ( hinst, "DllUnregisterServer" );        // If it was found, we can operate on the file, so add it to        // our list of files (m_lsFiles).        if ( NULL != pfn )            {            m_lsFiles.push_back ( szFile );            }        FreeLibrary ( hinst );        }   // end for

    最后一步就是(在最后一个if块中)添加文件名到m_lsFiles中。m_lsFiles是一个保存字符串的STL列表集。这个列表在稍后,就是当我们遍历所有文件注册和卸载的时候将被用到。

    在Initialize()的最后要做的就是释放资源并返回恰当的值给Explorer。

    // Release resources.    GlobalUnlock ( stg.hGlobal );    ReleaseStgMedium ( &stg );    // If we found any files we can work with, return S_OK.  Otherwise,    // return E_INVALIDARG so we don't get called again for this right-click    // operation.    return ( m_lsFiles.size() > 0 ) ? S_OK : E_INVALIDARG;}

    如果你看一眼例子项目代码的话,你会发现我不得不都过查看文件的文件名来计算出哪个目录正在被查看。你也许会纳闷为什么我不用pidlFolder参数。虽然在pidlFolder的文档中,它被解释为“包含正在显示上下文菜单的项目的文件夹的项目标志列表(the item identifier list for the folder that contains the item whose context menu is being displayed)(很抱歉我不能把这句话翻译好,贴出原文供参考)”。可是,我在Windows 98 上测试的时候,这个参数总是为NULL,所以它毫无用处。

添加我们的菜单项

    接下来的是IContextMenu方法。和以前一样,你需要添加IContextMenuCDllRegShlExt实现的接口列表中。再一次的,做这些的步骤在第一部分中。

    我们将添加两个菜单项到菜单中,一个为注册选中的文件,一个是卸载它们。这些项看起来如下:

    我们的QueryContextMenu()实现和第一部分一样开始。我们检查uFlags,如果CMF_DEFAULTONLY标志存在的话立即返回。 

HRESULT CDLLRegShlExt::QueryContextMenu (    HMENU hmenu,    UINT  uMenuIndex,    UINT  uidFirstCmd,    UINT  uidLastCmd,    UINT  uFlags ){UINT uCmdID = uidFirstCmd;    // If the flags include CMF_DEFAULTONLY then we shouldn't do anything.    if ( uFlags & CMF_DEFAULTONLY )        {        return MAKE_HRESULT ( SEVERITY_SUCCESS, FACILITY_NULL, 0 );        }

    下面,我们添加"Register servers"菜单项。这儿有些新东西:我们给菜单项设置了位图。这和WinZip的菜单有点儿相似,也在菜单命令旁边显示一个小图标。

    // Add our register/unregister items.    InsertMenu ( hmenu, uMenuIndex, MF_STRING | MF_BYPOSITION, uCmdID++,                 _T("Register (s)") );    // Set the bitmap for the register item.    if ( NULL != m_hRegBmp )        {        SetMenuItemBitmaps ( hmenu, uMenuIndex, MF_BYPOSITION, m_hRegBmp, NULL );        }    uMenuIndex++;

    SetMenuItemBitmaps()API函数我们宰菜单旁显示一个小齿轮的方法。注意uCmdID是自增加的,这样下一次我们调用InsertMenu(),它的命令ID将会比前一个大1。在这步骤的最后,uMenuIndex 被增加是因为我们的第二个菜单项将被显示在第一个之后。

    接着说第二个菜单项。它和第一个非常相似。

    InsertMenu ( hmenu, uMenuIndex, MF_STRING | MF_BYPOSITION, uCmdID++,                 _T("Unregister server(s)") );    // Set the bitmap for the unregister item.    if ( NULL != m_hUnregBmp )        {        SetMenuItemBitmaps ( hmenu, uMenuIndex, MF_BYPOSITION, m_hUnregBmp, NULL );        }

    最后,我们告诉Explorer我们添加了几个菜单项。

    return MAKE_HRESULT ( SEVERITY_SUCCESS, FACILITY_NULL, 2 );

提供敏感帮助和动词

    和前面的一样,当Explorer需要显示敏感帮助或者获得动词的时候,GetCommandString()方法被调用。和前一个稍稍不同的是我们添加了2个菜单项,所以我们必须首先检查uCmdID参数来知道Explorer正在呼叫哪个菜单项。

#include <atlconv.h>HRESULT CDLLRegShlExt::GetCommandString (     UINT  uCmdID,    UINT  uFlags,     UINT* puReserved,    LPSTR szName,    UINT  cchMax ){LPCTSTR szPrompt;    USES_CONVERSION;    if ( uFlags & GCS_HELPTEXT )        {        switch ( uCmdID )            {            case 0:                szPrompt = _T("Register all selected COM servers");            break;            case 1:                szPrompt = _T("Unregister all selected COM servers");            break;            default:                return E_INVALIDARG;            break;            }

    如果uCmdID为0,那么我们正在调用第一个(register)。如果为1,则在调用第二个(unregister)。在确定帮助字符串之后,我们将它拷贝到提供的缓存当中,必要的话,先将它转换成Unicode形式。

        // Copy the help text into the supplied buffer.  If the  wants        // a Unicode string, we need to case szName to an LPCWSTR.        if ( uFlags & GCS_UNICODE )            {            lstrcpynW ( (LPWSTR) szName, T2CW(szPrompt), cchMax );            }        else            {            lstrcpynA ( szName, T2CA(szPrompt), cchMax );            }        }

    在这个扩展中,我同样也写了代码提供一个动词。然而,我在Windows 98下测试的时候,Explorer从来不调用GetCommandString()来获取一个动词。我甚至写了一个在DLL中调用ShellExecute()的测试程序然后试图使用动词,但是它还是不工作。我不知道这个情况在Windows NT下是否会有不同。这儿,我忽略了那些动词相关的代码,如果你感兴趣的话,你可以在例子项目中找到。

执行用户的选择

    当用户点击我们菜单中的一个时,Explorer调用我们的InvokeCommand()方法。InvokeCommand()首先检查了lpVerb的高位字(high word)。如果它是非零的,则它是被调用的动词的名称,因为我们知道动词不能正常工作(至少在Win 98下),我们将它忽略了。否则,如果它的低位字(low word)是0或1,那么我们知道其中有一个菜单项目被点击了。

HRESULT CDllRegShlExt::InvokeCommand ( LPCMINVOKECOMMANDINFO pCmdInfo ){    // If lpVerb really points to a string, ignore this function call and bail out.    if ( 0 != HIWORD( pInfo->lpVerb ))        return E_INVALIDARG;    // Check that lpVerb is one of our commands (0 or 1)    switch ( LOWORD( pInfo->lpVerb ))        {        case 0:        case 1:            {            CProgressDlg dlg ( &m_lsFiles, pInfo );            dlg.DoModal();            return S_OK;            }        break;        default:            return E_INVALIDARG;        break;        }}

    如果lpVerb是0或1,我们创建一个对话框(从ATL类CDialogImpl继承),然后向它传递文件名列表。

    所有实际的工作都在CProgressDlg类中完成。它的OnInitDialog()函数初始化列表控件,然后调用CProgressDlg::DoWork()DoWork()遍历在CDllRegShlExt::Initialize()中生成的文件名列表,然后调用文件中的合适的函数。基本代码如下;并不完全,因为我删掉了错误检查和填充列表控件的部分。不过这已经足够向大家演示如何遍历一个文件列表并执行每一个。

void CProgressDlg::DoWork(){HRESULT (STDAPICALLTYPE* pfn)();string_list::const_iterator it, itEnd;HINSTANCE hinst;LPCSTR    pszFnName;HRESULT   hr;WORD      wCmd;    wCmd = LOWORD ( m_pCmdInfo->lpVerb );    // We only support 2 commands, so check the value passed in lpVerb.    if ( wCmd > 1 )        return;    // Determine which function we'll be calling.  Note that these strings are    // not enclosed in the _T macro, since GetProcAddress() only takes an    // ANSI string for the function name.    pszFnName = wCmd ? "DllUnregisterServer" : "DllRegisterServer";    for ( it = m_pFileList->begin(), itEnd = m_pFileList->end();          it != itEnd;          it++ )        {        // Try to load the next file.        hinst = LoadLibrary ( it->c_str() );        if ( NULL == hinst )            continue;        // Get the address of the register/unregister function.        (FARPROC&) pfn = GetProcAddress ( hinst, pszFnName );        // If it wasn't found, go on to the next file.        if ( NULL == pfn )            continue;        // Call the function!        hr = pfn();

    我需要解释一下那个for循环,因为STL集合类是有点令人胆战心惊的,如果你不习惯使用它的话。m_pFileList是一个指向在CDllRegShlExt类中的m_lsFiles列表的指针。(这个指针被传递给了CProgressDlg的构造器。)STL列表集有一个类型叫做const_iterator,这是一个相似于MFC中POSITION类型的抽象实体。一个const_iterator变量像一个列表中常量对象的指针,所以这个遍历器(iterator)可以使用->访问它本身。遍历器可以使用++ 来自增实现在列表中前进。

    所以,这个for循环的初始化表达式调用list::begin()来获取一个遍历器“指向”列表中的第一个字符串,然后调用list::end()来获取一个遍历器“指向”列表的“末尾”,最后一个字符串的位置。 (我把这些词语放在引号里是为了强调指向,开始,和末尾的概念都是被const_iterator类型抽象了的,而且必须通过const_iterator的方法[像begin()]或者操作符[像++]。)这些遍历器被分别地赋给ititEnd。 这个循环一直进行着,直到it等于itEnd;意思是,当it还没有到达列表的“末尾”时。这个遍历器it将会在循环过程每次自增加,这样它可以每次到达一个列表中的字符串。

    在遍历其中,表达式it->c_str() 使用->操作符。因为it像一个指向string的指针(记住,m_pFileList是一个STL string的列表),it->c_str()it当前所指向的string中调用c_str()函数。c_str()返回一个C类型的字符串指针,既然这样,就是一个LPCTSTR

    DoWork()的余下部分是释放内存和错误检查。你可以从例子项目的ProgressDlg.cpp文件中获取所有代码。

    (我刚刚意识到叫一个变量为"it",是多么的奇怪。很抱歉!) :)

注册外壳扩展

    这个DllReg扩展对可执行文件进行操作,所以我们注册它被EXE,DLL和OCX文件调用。和第一部分中一样,我们可以在RGS脚本中做这些事,DllRegShlExt.rgs。下面是注册我们的扩展为一个对于上述扩展名文件的上下文菜单扩展必需的脚本。

HKCR{    NoRemove dllfile    {        NoRemove shellex        {            NoRemove ContextMenuHandlers            {                ForceRemove DLLRegSvr = s '{8AB81E72-CB2F-11D3-8D3B-AC2F34F1FA3C}'            }        }    }    NoRemove exefile    {        NoRemove shellex        {            NoRemove ContextMenuHandlers            {                ForceRemove DLLRegSvr = s '{8AB81E72-CB2F-11D3-8D3B-AC2F34F1FA3C}'            }        }    }    NoRemove ocxfile    {        NoRemove shellex        {            NoRemove ContextMenuHandlers            {                ForceRemove DLLRegSvr = s '{8AB81E72-CB2F-11D3-8D3B-AC2F34F1FA3C}'            }        }    }}

    RGS文件的格式,以及关键词NoRemoveForceRemove第一部分已经解释过了,如果你忘了他们的意思的话。 

    正如我们前一个扩展一样,在NT/2000下,我们需要添加我们的扩展到“认证的(approved)”扩展列表当中。实现这个过程的代码在 DllRegisterServer()DllUnregisterServer()函数中。我不想展示这些代码,因为它仅仅是一些简单的注册表访问,但是你可以从例子项目中中到这些代码。

看起来应该什么样呢?

    当你点击我们其中的一个菜单的时候,对话框就会出现,显示操作的结果:

    列表控件显示了每个文件的文件名和操作是否成功。当你选中一个项时,一个更详细的消息将被显示在下方。如果失败的话,将有调用失败的描述。

注册扩展的其他方法

    到现在为止,我们的扩展只被确定的文件类型调用。通过在HKCR\*下注册成为一个上下文菜单扩展使得被任何文件操作调用成为可能:

HKCR{    NoRemove *    {        NoRemove shellex        {            NoRemove ContextMenuHandlers            {                ForceRemove DLLRegSvr = s '{8AB81E72-CB2F-11D3-8D3B-AC2F34F1FA3C}'            }        }    }}

    HKCR\*键被所有文件调用的外壳扩展。注意文档中所说的该扩展也被其他外壳对象所调用(文件,目录,虚拟文件夹,控制面板项等等),但是我在测试中所见到的并不是这样。这些扩展仅仅被文件系统中的文件所调用。

    在外壳版本4.71以上,还有一个叫做HKCR\AllFileSystemObjects的键。如果我们在这个键下注册,我们的扩展将被文件系统中所有的文件和目录调用,根目录除外。(根目录调用的扩展在HKCR\Drive下注册。)然而,当我在这个键下注册的时候我看到一些奇怪的现象。“发送到”菜单也使用这个键,而它混在了DllReg菜单中间:

    你同样可以编写一个操作目录的上下文菜单扩展。要这样的例子的话,请看我的文章:
   A Utility to Clean Up Compiler Temp Files(一个清除编译临时文件的实用工具)。(译者:确实是个好玩艺 :))

    最后,在外壳版本4.71以上,你可以使你的上下文菜单在用户右键单击一个正在查看目录(包括桌面)的资源管理器窗口背景时被调用。为了使你的扩展被这么调用,你必须在HKCR\Directory\Background\shellex\ContextMenuHandlers键下注册。使用这个方法,你可以向你的桌面上下文菜单中添加菜单项目或者其他任何目录。传递给IShellExtInit::Initialize()的参数有点儿不同,我会在我以后的文章中加以说明。

待续……

    接着的第三部分我们将实践一种新的扩展,查询。它将显示一些外壳对象的弹出式描述。我还将向你展示如何在外壳扩展中使用MFC。

    你可以从下面的网址获得这个和其他文章的最新版本:http://home.inreach.com/mdunn/code/

0

Shell编程 – 傻瓜教程1


    外壳扩展( Extention)是一个能向外壳(资源管理器)添加一些功能的COM对象。这有很多的内容,但是却很少有关于它们的易懂的文档告诉我们如何去编写这些外壳(Shell)程序。如果你想做对外壳很深入的了解,我极力向你推荐Dino Esposito 的非常好的一本书《Visual C++ Windows Shell Programming》。但是对于那些没有这本书并且仅仅关心如何去编写外壳扩展的人,我写的一指南将会令你非常惊讶,如果并非如此的话也能给你理解如何编写外壳扩展提供很好的帮助。要阅读这一指南,确保你对COMATL要相当熟悉。

第一部分包括了对外壳扩展的概要的介绍,并提供了一个上下文菜单扩展的例程来使你对以后的部分中充满兴趣。

什么是外壳扩展呢?

这有两部分,外壳和扩展(extension)。外壳指的是资源管理器(Explorer),而扩展是指当一个预订的事件(如:右键单击一个.doc文档)发生时,被资源管理器调用的你写的代码。所以以个外壳扩展是一个向资源管理器添加特色的COM对象。

一个外壳扩展是一个进程中服务器,它实现了一些与资源管理器通信的借口。而在我看来,ATL是快速实现一个扩展并使它运行的最简单的方法,因为你不用为一遍又一遍的写QueryInterface()AddRef()而大伤脑筋。而且在Windows NT/2000下调试扩展也变得更为容易。

有很多种的扩展,每种扩展在不同的事件发生时被调用。下面是一些比较通用的类型和它们被调用的情况:

类型

什么时候被调用

可以做什么

上下文菜单

用户在文件或目录右键单击时。在外壳扩展4.71版本以上,在目录窗口的背景上右键单击也将被调用。

向上下文菜单添加项目。

属性单

文件的属性单被显示时。

向属性单添加一个属性页。

拖扔

用户右键拖动项目并把它扔在一个目录窗口活着桌面上时。

添加项目至上下文菜单。

用户拖一个项目并把它扔到一个文件上时。

任何你想做的事。

查询信息(外壳版本4.71+)

用户鼠标在一个文件或像我的电脑一样的其他外壳对象上悬停时。

返回一个资源管理器在工具条提示上的字符串。

到现在为止你可能为什么一个扩展看起来想在资源管理器里。如果你安装了WinZip(有谁没有吗?),它就包括了许多种的外壳扩展,其中一个就是上下文句柄。下面世WinZip 8 为了压缩文件添加到上下文菜单的截图:

WinZip包含了添加菜单项目的代码,并提供敏感帮助(显示在资源管理器状态条的文本),并在用户选择WinZip命令之一时起作用。

WinZip还包含了拖和扔的句柄。这个类型和上下文菜单扩展非常类似,但是它仅仅在用户通过鼠标右键拖动一个文件时才被调用。下面是WinZip的拖扔句柄如何添加上下文菜单:

还有很多种其他类型(微软一直往新版本的Windows里添加更多内容)。到现在,我们已经看到了上下文菜单扩展,因为它非常容易编写,我们将很容易的看到它的结果(很快就能满意)。

在我们开始编码以前,有一些提示,它将使我们做起来更加容易。当你促成一个外壳扩展被资源管理器调用的时候,它将在内存中呆上一小会儿,从而使它不能立即被重建(rebuild)。为了使资源管理器更加频繁的卸载这些扩展,创建这个注册表键:

HKLM\Software\Microsoft\Windows\CurrentVersion\Explorer\AlwaysUnloadDLL

并把它的默认值设为”1”。在Windows 9x系列中,这是最好的方法。在NT/2000,到如下的键:

HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer

创建一个叫做DesktopProcess的双字节值,使它的值为1。这使得桌面和任务栏运行在一个进程中,后发的资源管理器运行在它自己的进程里。这就意味着你可以使用一个单独的资源管理器窗口来调试,并且当你关掉它的时候,你的DLL也会自动的被卸载,避免了该文件仍然在使用得问题。要使得你的注册表修改生效的话,你必须注销并且重新登录。

我将稍晚一些解释如何在Win 9x下进行调试。

开始一个上下文菜单扩展它能做什么?

让我们开始简单的做一个扩展,它仅仅弹出一个消息框表示它已经在工作了。我们将对扩展名为.txt的文件设置一个钩子,这样当用户右键单击一个文本文件的时候,我们的扩展就能被调用了。

使用AppWizard 开始

好了,现在是我们开始的时候了。那是什么?我还没有告诉你如何使用神秘的外壳扩展接口?不要担心,我将在接下来的过程中为你解释。我发现如果一个概念被解释,有一个例子更容易明白,通过例子代码你很快就能理解。我将会先解释任何东西,然后给出代码,但是我发现还是不容易吸收。总之,启动你的MSVC吧,我们要开始了。

运行AppWizard ,做一个新的ATL COM wizard app。我们叫它SimpleExt 。在向导中保持所有默认选项,单击完成。我们现在就有了一个空的将会生成DLLATL项目,但是我们必须添加自己的外壳扩展COM对象。在ClassView树中,右键单击SimpleExt classes 项,选择New ATL Object

ATL Object 向导,第一面板已经选择了Simple Object ,只要单击下一步就行了。在第二面板中,在Short Name 编辑控件中输入SimpleShlExt ,然后单击确定(面板中的其它的编辑框将会自动完成)。这就创建了一个类名为CSimpleShlExt 的类,它包含了实现一个COM对象的基本代码。我们将向这个类添加我们的代码。

初始化接口

当我们的外壳扩展被装载的时候,资源管理器调用我们的QueryInterface()函数获取一个指向IShellExtInit 接口的指针。这个接口只有一个方法,Initialize(),它的原型如下:

HRESULT IShellExtInit::Initialize (
    LPCITEMIDLIST pidlFolder,
    LPDATAOBJECT pDataObj,
    HKEY hProgID );

资源管理器使用这个方法给我们不同的信息。pidlFolder 是包含有正在被作用的文件的文件夹的PIDL(PIDL[pointer to an ID list]是唯一标志外壳中任一对象(无论是否是文件系统对象)的数据结构。pDataObj 是一个IDataObject 接口指针,通过它我们可以获得被作用的文件的文件名。hProgID 是一个打开的HKEY ,通过它我们可以访问包含有我们的DLL注册数据的注册表键。在这个简单的扩展中,我们只需要用到pDataObj参数。

添加这个接口方法到我们的COM 对象中,先打开SimpleShlExt.h 文件,并添加如下用红色书写的代码行:

#include <shlobj.h>
#include <comdef.h>
 
 ATL_NO_VTABLE CSimpleShlExt : 
    public CComObjectRootEx<CComSingleThreadModel>,
    public CComCoClass<CSimpleShlExt, &CLSID_SimpleShlExt>,
    public IDispatchImpl<ISimpleShlExt, &IID_ISimpleShlExt, &LIBID_SIMPLEEXTLib>,
    public IShellExtInit
{
BEGIN_COM_MAP(CSimpleShlExt)
    COM_INTERFACE_ENTRY(ISimpleShlExt)
    COM_INTERFACE_ENTRY(IDispatch)
    COM_INTERFACE_ENTRY(IShellExtInit)
END_COM_MAP()

这个COM_MAP是说明了ATL如何实现它的QueryInterface()。这个列表告诉ATL其他使用QueryInterface()的程序可以从我们这儿获得什么。

接着,在类的声明当中,添加Initialize()函数。此外,我们还需要一个保存文件名的变量:

protected:
    TCHAR m_szFile [MAX_PATH];
 
public:
    // IShellExtInit
    STDMETHOD(Initialize)(LPCITEMIDLIST, LPDATAOBJECT, HKEY);

接下来,在SimpleShlExt.cpp 文件中,添加该函数的定义:

HRESULT CSimpleShlExt::Initialize ( 
    LPCITEMIDLIST pidlFolder,
    LPDATAOBJECT pDataObj,
    HKEY hProgID )

我们所要做的就是获得被右键单击的文件的文件名,并把它显示在一个消息框中。如果有很多个文件被选中,你可以通过pDataObj 接口指针访问它们。但是为了保持该例子的简单性,我只要获得第一个文件的文件名。

文件名被保存为与你使用WS_EX_ACCEPTFILES样式拖和扔一个文件到窗口时用到的一个相同的格式。那就意味着,我们获得文件名使用了相同的API: DragQueryFile()。我们通过获得包含在IDataObject 中的数据的句柄开始这个函数:

{
FORMATETC fmt = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
STGMEDIUM stg = { TYMED_HGLOBAL };
HDROP     hDrop;
 
    // Look for CF_HDROP data in the data object.
    if ( FAILED( pDataObj->GetData ( &fmt, &stg )))
        {
        // Nope! Return an "invalid argument" error back to Explorer.
        return E_INVALIDARG;
        }
 
    // Get a pointer to the actual data.
    hDrop = (HDROP) GlobalLock ( stg.hGlobal );
 
    // Make sure it worked.
    if ( NULL == hDrop )
        {
        return E_INVALIDARG;
        }

要注意,错误检查是极其重要的,尤其是指针。因为我们的扩展运行在资源管理器的进程空间当中,如果我们的程序毁坏的话,同样会让资源管理器也毁坏的。在Win 9x下,这可能就意味着重新启动。

现在,我们有了一个HDROP 句柄,我们可以获得我们需要的文件名了。

    // Sanity check – make sure there is at least one filename.
UINT uNumFiles = DragQueryFile ( hDrop, 0xFFFFFFFF, NULL, 0 );
 
    if ( 0 == uNumFiles )
        {
        GlobalUnlock ( stg.hGlobal );
        ReleaseStgMedium ( &stg );
        return E_INVALIDARG;
        }
 
HRESULT hr = S_OK;
 
    // Get the name of the first file and store it in our member variable m_szFile.
    if ( 0 == DragQueryFile ( hDrop, 0, m_szFile, MAX_PATH ))
        {
        hr = E_INVALIDARG;
        }
 
    GlobalUnlock ( stg.hGlobal );
    ReleaseStgMedium ( &stg );
 
    return hr;
}

如果我们返回E_INVALIDAR,在右键单击事件发生时,资源管理器将不会再调用我们的扩展。如果我们返回S_OK ,那么资源管理器将会再次调用QueryInterface()来获得我们将要添加的另一个接口指针:IContextMenu

和上下文菜单交互的接口

一旦资源管理器初始化了我们的扩展,它将会调用IContextMenu 的方法让我们添加菜单项目、敏感帮助并完成用户的选择。

向我们的扩展中添加IContextMenu 接口和添加IShellExtInit相类似。打开SimpleShlExt.h并添加一下红颜色的代码:

class ATL_NO_VTABLE CSimpleShlExt : 
    public CComObjectRootEx<CComSingleThreadModel>,
    public CComCoClass<CSimpleShlExt, &CLSID_SimpleShlExt>,
    public IDispatchImpl<ISimpleShlExt, &IID_ISimpleShlExt, &LIBID_SIMPLEEXTLib>,
    public IShellExtInit,
    public IContextMenu
{
BEGIN_COM_MAP(CSimpleShlExt)
    COM_INTERFACE_ENTRY(ISimpleShlExt)
    COM_INTERFACE_ENTRY(IDispatch)
    COM_INTERFACE_ENTRY(IShellExtInit)
    COM_INTERFACE_ENTRY(IContextMenu)
END_COM_MAP()

接着添加IContextMenu 方法的原型:

public:
    // IContextMenu
    STDMETHOD(GetCommandString)(UINT, UINT, UINT*, LPSTR, UINT);
    STDMETHOD(InvokeCommand)(LPCMINVOKECOMMANDINFO);
    STDMETHOD(QueryContextMenu)(HMENU, UINT, UINT, UINT, UINT);

更改上下文菜单

IContextMenu 3个方法。第一个,QueryContextMenu(),让我们更改菜单。它的原型为:

HRESULT IContextMenu::QueryContextMenu (
    HMENU hmenu,
    UINT  uMenuIndex, 
    UINT  uidFirstCmd,
    UINT  uidLastCmd,
    UINT  uFlags );

hmenu 是上下文菜单的句柄。uMenuIndex 是我们开始添加我们的菜单项目的开始位置。 uidFirstCmd uidLastCmd 是我们可以给菜单项目使用的命令ID值的范围。uFlags 指出为什么资源管理器正在调用QueryContextMenu(),这我们将在以后看到。

有关它的返回值你将会得到不同的答案,如果你问不同的人的话。Dino Esposito 的书上说它使被QueryContextMenu()添加的菜单项目的号码。MSDN上关于VC 6部分说它是最后一个被添加的菜单项目的命令ID加上1。最新的MSDN文档有如下说明:

设置代码的值[HRESULT返回的]为被分配的最大的命令ID偏移加上1。例如,假定idCmdFirst被设置为5,你添加了3个菜单项目分别使用命令ID578。它的返回值将是MAKE_HRESULT(SEVERITY_SUCCESS, 0, 8 – 5 + 1)

到我现在所写的所有代码中,我接受了Dino的解释,这样工作的很好。事实上,他的制作返回值的方法和在线MSDN的方法是相同的,在你使用uidFirstCmd开始添加你的菜单项目时开始计数,每添加一个增加1

我们的简单的扩展将仅仅添加一个菜单项目,所以QueryContextMenu()函数相当简单:

HRESULT CSimpleShlExt::QueryContextMenu (
    HMENU hmenu,
    UINT  uMenuIndex, 
    UINT  uidFirstCmd,
    UINT  uidLastCmd,
    UINT  uFlags )
{
    // If the flags include CMF_DEFAULTONLY then we shouldn't do anything.
    if ( uFlags & CMF_DEFAULTONLY )
        {
        return MAKE_HRESULT ( SEVERITY_SUCCESS, FACILITY_NULL, 0 );
        }
 
    InsertMenu ( hmenu, uMenuIndex, MF_BYPOSITION, uidFirstCmd, _T("SimpleShlExt Test Item") );
 
    return MAKE_HRESULT ( SEVERITY_SUCCESS, FACILITY_NULL, 1 );
}

我们首先要做的就是检查uFlags。你可以在MSDN查询所有的标志列表,但是对于上下文菜单扩展来说,只有一样是重要的:CMF_DEFAULTONLY。这个标志告诉名字空间扩展仅仅添加默认菜单项目。如果这个标志在的话,外壳扩展将不会添加任何菜单项目。这就是为什么当CMF_DEFAULTONLY存在的时候我们立即返回0的原因。如果该标志不存在,我们更改菜单(使用hmenu 句柄),然后返回1告诉外壳我们添加了一个菜单项目。

在状态条显示敏感帮助

IContextMenu 中下一个可以调用的方法是GetCommandString()。如果用户在资源管理器窗口中右键单击了一个文本文件的时候,或者选中一个文本文件,然后单击“文件”菜单,状态条上将显示敏感帮助。我们的GetCommandString() 函数将会返回一个让资源管理器显示得字符串。

GetCommandString()函数原型如下:

HRESULT IContextMenu::GetCommandString (
    UINT idCmd,
    UINT uFlags,
    UINT *pwReserved,
    LPSTR pszName,
    UINT cchMax );

idCmd 是一个基于0的指明哪个菜单项目被选中的数。因为我们仅仅添加了一个菜单项,idCmd 将总是为0。但是如果我们添加了,我是说,3个的话,idCmd 将会是0,1或者2uFlags是另一个标志组。我将会在后面进行描述。我们可以忽略pwReservedpszName 是一个指向一个被外壳所拥有的缓存的指针,该缓存保存被显示的帮助字符串。cchMax 是缓存的大小。返回值是HRESULT常量,例如S_OKE_FAIL

GetCommandString()同样能被用来获得菜单项的“动词”。“动词”是一个标志作用于文件的动作的字符串,它是独立于语言的。有关ShellExecute()的文档作了更多的说明,有关“动词”的主题更适合在另一篇文章说明,这儿简要说明的是列在注册表中的动词(比如说”open””print”),或者那些有上下文菜单扩展动态创建的“动词”。这使得在外壳扩展中实现的行为可以被ShellExecute()调用。

总之,我提及所有这些的原因是我们不得不确定为什么GetCommandString()被调用。如果资源管理器需要一个敏感帮助字符串的时候,我们就提供。如果资源管理器请求一个“动词”的话,我们将忽略它。这是uFlags起作用的地方。如果uFlags GCS_HELPTEXT 的位被设置的话,那么资源管理器将请求敏感帮助。附加的,如果GCS_UNICODE位被设置,我们必须返回一个Unicode字符串。

我们的GetCommandString() 的代码看起来应该像下面这样:

#include <atlconv.h>  // for ATL string conversion macros
 
HRESULT CSimpleShlExt::GetCommandString (
    UINT  idCmd,
    UINT  uFlags,
    UINT* pwReserved,
    LPSTR pszName,
    UINT  cchMax )
{
    USES_CONVERSION;
 
    // Check idCmd, it must be 0 since we have only one menu item.
    if ( 0 != idCmd )
        return E_INVALIDARG;
 
    // If Explorer is asking for a help string, copy our string into the
    // supplied buffer.
    if ( uFlags & GCS_HELPTEXT )
        {
        LPCTSTR szText = _T("This is the simple shell extension's help");
 
        if ( uFlags & GCS_UNICODE )
            {
            // We need to cast pszName to a Unicode string, and then use the
            // Unicode string copy API.
            lstrcpynW ( (LPWSTR) pszName, T2CW(szText), cchMax );
            }
        else
            {
            // Use the ANSI string copy API to return the help string.
            lstrcpynA ( pszName, T2CA(szText), cchMax );
            }
 
        return S_OK;
        }
 
    return E_INVALIDARG;
}

没什么奇特的;我只是把字符串编码并且把它转换为合适的字符集。如果你以前从来都没有使用过ATL变换宏,你干脆先看看它们,因为这将我使更容易理解传递一个Unicode字符串到COM方法和OLE函数中。在上面的代码中,我使用了T2CWT2CA 分别将TCHAR字符串转换为UnicodeANSI。在函数头部的USES_CONVERSION 宏声明了一个变换宏使用的局部变量。

一个需要注意的重要事项是lstrcpyn()API函数保证了目标字符串是以null结束的。这是它和CRT函数strncpy()的不同之处。如果源字符串的长度大于或等于cchMax时, strncpy() 并不添加结束符null。我建议你总是使用lstrcpyn(),这样你就不用不得不在strncpy()之后添加检查来保证字符串是null结束的。

执行用户的选择

最后一个IContextMenu方法是InvokeCommand()。这个方法将在用户单击我们添加的那个菜单项目时被调用。它的原型如下:

HRESULT IContextMenu::InvokeCommand ( LPCMINVOKECOMMANDINFO pCmdInfo );

CMINVOKECOMMANDINFO 结构里有很多的信息,但是根据我们现在的意图,我们只需要关心lpVerbhwnd lpVerb 有双重的任务——它既可以是被调用的“动词”的名称,也可以是一个用以告诉我们哪个菜单项被选中地索引。hwnd 是资源管理器窗口的句柄,在那儿,用户调用了我们的扩展。

我们检查lpVerb ,因为我们只添加了一个菜单项,所以如果它为0,则我们的菜单被点击了。我能想到的最简单的事就是弹出一个消息框,所以我们就这么做。这个消息框显示了选中的文件的文件名,证明它的确是在工作。

HRESULT CSimpleShlExt::InvokeCommand ( LPCMINVOKECOMMANDINFO pCmdInfo )
{
    // If lpVerb really points to a string, ignore this function call and bail out.
    if ( 0 != HIWORD( pCmdInfo->lpVerb ))
        return E_INVALIDARG;
 
    // Get the command index - the only valid one is 0.
    switch ( LOWORD( pCmdInfo->lpVerb ))
        {
        case 0:
            {
            TCHAR szMsg [MAX_PATH + 32];
 
            wsprintf ( szMsg, _T("The selected file was:\n\n%s"), m_szFile );
 
            MessageBox ( pCmdInfo->hwnd, szMsg, _T("SimpleShlExt"),
                         MB_ICONINFORMATION );
 
            return S_OK;
            }
        break;
 
        default:
            return E_INVALIDARG;
        break;
        }
}

注册外壳扩展

到现在为止,我们已经实现了我们所有的COM接口。但是……如何使资源管理器使用我们的扩展呢?ATL自动生成了注册我们的DLL为一个COM服务器的代码,但是它仅仅是让其它程序来使用我们的DLL。为了告诉资源管理器我们的扩展存在,我们必须在保持文本文件的注册表键下注册它:

HKEY_CLASSES_ROOT\txtfile

在那个键下面,一个叫做ShellEx 的键保存了一个对于文本文件将被调用的外壳扩展列表。在ShellEx下,ContextMenuHandlers 键保存了一个上下文菜单扩展的列表。每一个扩展在ContextMenuHandlers下创建一个字键,并把他的默认值设置为它的GUID。所以,为我们的扩展,我们创建如下键:

HKEY_CLASSES_ROOT\txtfile\ShellEx\ContextMenuHandlers\SimpleShlExt

并把它的默认值设置为我们的GUID

"{5E2121EE-0300-11D4-8D3B-444553540000}"

然而,你不用自己做这件事。如果你在FileView页查看你得文件列表时,你会发现SimpleShlExt.rgs。这是一个由ATL解析的文本文件,它告诉ATL当这个服务器被注册时该添加什么键,当被反注册时又该删除什么键。下面我们指定了要添加的注册表入口:

HKCR
{
    NoRemove txtfile
    {
        NoRemove ShellEx
        {
            NoRemove ContextMenuHandlers
            {
                ForceRemove SimpleShlExt = s '{5E2121EE-0300-11D4-8D3B-444553540000}'
            }
        }
    }
}

它以"HKCR"——HKEY_CLASSES_ROOT的缩写——开头,每一行是注册表键名称。关键词NoRemove 意味着当该服务器被反注册时该键不能被删除。最后一行有点复杂。关键词ForceRemove 意思是如果该键存在,那么在该键被写之前先删除它。这一行剩下的部分指定了一个将被保存在SimpleShlExt键的默认值中的字符串(那就是”s”的意思)

在这儿,我需要说明一点。我们注册扩展时的键是HKCR\txtfile。然而,这个名称"txtfile" 并不是一个永久的或预先知道的。如果你查看一下HKCR\.txt ,那个键的默认值是这个名称被保存的地方。这就两个侧面效果:

  • 我们将不能可靠的使用RGS脚本,因为"txtfile"可能不是正确的键名。
  • 其他的一些文本编辑器可能被安装,它们同.TXT文件相关联。如果它们改变了 HKCR\.txt键的默认值,所有存在的外壳扩展都将会停止工作。

看起来,这的确是我设计的缺陷。我想微软也在考虑同样的事,因为最近创建的扩展,像QueryInfo扩展,是在.txt键下注册的。

好了,说明到这儿。有一个最终的注册细节。在Win NT/2000下,我们必须自己将我们的扩展方到一个“被认可的”扩展列表当中。如果我们不这么做的话,那些非管理员用户将不会壮在我们的扩展。这个列表被保存在:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved

在这个键下,我们创建一个字符串值它的名称是我们的GUID。字符串的内容可以是任何东西。做这些事情的代码在我们的DllRegisterServer()DllUnregisterServer()函数当中。我并不想把这些呆马列在这儿,因为这只是简单的注册表访问。你可以从本文的例子项目当中找到它们。

调试外壳扩展

最终,你写成了这个相当不容易的扩展,然后你将会调试它。打开你的项目设置(Project->Settings),到栏,在"Executable for debug session"编辑框中输入资源管理器的全路径,例如:"C:\windows\explorer.exe"。如果你使用的是NT2000,而且你已经设置过了DesktopProcess 注册表项,那么在你按F5开始调试的时候,会有一个新的资源管理器窗口打开。只要你在那个窗口工作,以后重建DLL时你将不会有问题,因为当你关掉窗口时,你的扩展也被卸载了。

Windows 9x下,恐怕你不得不在调试之前关闭你的外壳。单击“开始”->“关闭系统”。按住Ctrl+Alt+Shift然后点击“取消”。这将关闭资源管理器,然后你看见任务栏消失了。切换到MSVC然后按F5开始调试。按Shift+F5关闭资源管理器停止调试。当你做完调试的时候,你可以运行Explorer重新正常启动你的外壳。

它看起来是什么样的?

下面是我们添加的项目看起来的样子:

这就是我们的菜单!

下面是有敏感帮助时资源管理器的状态栏的样子:

而下面是消息框的样子,它显示了被选中的文件的文件名:

      本例程代码下载地址(11K)http://www.codeproject.com/shell/ShellExtGuide1/ShellExtGuide1_demo.zip

下一部分……

接着的第二部分,一个新的上下文菜单扩展将会告诉你如何同时对多个文件进行操作。

你可以从下面的网址获得这个和其他文章的最新版本:http://home.inreach.com/mdunn/code/

 

关于翻译:

      这是我第一次翻译文章,文章来自著名的http://www.codeproject.com/,翻译之前我看了csdn的开发文档,发现还是空白,所以就像把它翻译了,也许有对它感兴趣的人。文章总共有9个部分。我没有太多的时间,只翻译了第一部分,也许能起到抛砖引玉的作用,让那些对外壳扩展不了解的人入个门,入了门的多个参考。更多的文章大家可以从http://www.codeproject.com/shell/ 找到。例子代码,原文也可以从那儿找到。我的emailmefish@163.net,头一次翻译,做得不好,任何意见、建议、鲜花、掌声、石头、带酒的啤酒瓶都将受到热烈欢迎……

0

IE编程 – ToolBar


关键字:Band,Desk Band,Explorer Band,Tool Band,浏览器栏,工具栏,桌面工具栏

一、引言
  最近,由于工作的要求,我需要在 上做一些开发工作。于是在 MSDN 上翻阅了一些资料,根据 MSDN 上的说明我用 ATL 胜利完成了“资本家老板”分配的任务。
(并且在白天睡觉的过程中梦到了老板给我加工资啦……)
现在,我把 MSDN 上的原文资料,经过翻译整理并把一个 ATL 的实现奉贤给 VCKBASE 上的朋友们。

二、概念
  在翻译的过程中,有两个词汇非常不好理解。第一个词是 Band 对象,词典中翻译为“镶边、裙子边、带子、乐队……”我的英文水平有限,实在不知道应该翻译为什么词汇更合适。于是我毅然决然地决定:在如下的论述中,依然使用 band 这个词!(什么?没听明白?我的意思就是说,我不翻译这个词了)但到底 Band 对象应该如何理解那?请看图一:


图一

  图一中画红圈的地方,分别称作“垂直的浏览器栏”、“水平的浏览器栏”、“工具栏”和“桌面工具栏”。这些“栏”,都可以在 IE 的“查看”菜单中或鼠标右键的上下文快捷方式菜单中显示或隐藏起来。这些界面窗口的实现,其实就是实现一种 COM 接口对象,而这个对象叫 band。这个概念实在是只能意会而无法言传的,我总不能在文章中把它翻译为“总是靠在 IE 主窗口边上的对象”吧?^_^
  另外,还有一个词叫 site。这个很好翻译,叫“站点”!。呵呵,我敢打包票,如果你要能理解这个翻译在计算机类文章中的含义,那就只能恭喜你了,你的智慧太高了。(都是学计算机软件的人,做人的差距咋就这么大呢?)在本篇文章中,site 可以这样理解:IE 的主框架四周,就好比是“汽车站”,那些 band 对象,就好比是“汽车”。band 汽车总是可以停靠在“汽车站”上。所以,site 就是“站点”,它也是 COM 接口的对象(IObjectWithSite、IInputObjectSite)。

三、原理

3.1 基本 band 对象
  Band 对象,从 4.71(IE 5.0) 开始提供支持。Band 是一个 COM 对象,必须放在一个容器中去使用,当然使用它们就好象使用普通窗口是一样的。IE 就是一个容器,桌面 也是一个容器,它们提供不同的函数功能,但基本的实现是相似的。
  Band 对象分三种类型,浏览器栏 band(Explorer bands)、工具栏 band(Tool Bands)和桌面工具栏(Desk bands),而浏览器栏 band 又有两种表现形式:垂直和水平的。那么 IE 和 Shell 如何区分并加载这些 bands 对象呢?方法是:你要对不同的 band 对象,在注册表中注册不同的组件类型(CATID)。

Band 样式

组件类型

CATID

垂直的浏览器栏 CATID_InfoBand 00021493-0000-0000-C000-000000000046
水平的浏览器栏 CATID_CommBand 00021494-0000-0000-C000-000000000046
桌面的工具栏 CATID_DeskBand 00021492-0000-0000-C000-000000000046

  IE 工具栏不使用组件类型注册,而是使用在注册进行 CLSID 的登记方式。详细情况见 3.3。
  在例子程序中,实现了全部四个类型的 band 对象,垂直浏览器栏(CVerticalBar)显示了一个 文件,并且实现了对 IE 主窗口浏览网页的导航等功能;水平的浏览器栏(CHorizontalBar)是一个编辑窗,它同步显示当前网页的 BODY 源文件内容;IE 工具栏(CToolBar)最简单,只是添加了一个空的工具栏;桌面工具栏(CDeskBar)实现了一个单行编辑窗口,你可以在上面输入命令行或文件名称,回车后它会执行 Shell 的打开动作。

3.2 必须实现的 COM 接口
  Band 对象是 IE 或 Shell 的进程内服务器,所以它被包装在 DLL 中。而作为 COM 对象,它必须要实现 IUnknown 和 IClassFactory 接口。(大家可以不同操心,因为我们用 ATL 写程序,这两个接口是不用我们自己写代码的。)另外,Band 对象还必须实现 IDeskBand、IObjectWithSite 和 IPersistStream 三个接口:
  IPersistStream 是持续性接口的一种。当 IE 加载 band 对象的时候,它通过这个接口的 Load 方法传递属性值给对象,让其进行初始化;而当卸载前,IE 则调用这个接口的 Save 方法保存对象的属性。用 ATL 实现这个接口很简单:

 ATL_NO_VTABLE Cxxx : 	......	public IPersistStreamInitImpl, // 添加继承	......{public:	BOOL m_bRequiresSave; // IPersistStreamInitImpl 所必须的变量......BEGIN_COM_MAP(CVerticalBar)	......	COM_INTERFACE_ENTRY2(IPersist, IPersistStreamInit)	COM_INTERFACE_ENTRY2(IPersistStream, IPersistStreamInit)	COM_INTERFACE_ENTRY(IPersistStreamInit)	......END_COM_MAP()BEGIN_PROP_MAP(Cxxx)...... // 添加需要持续性的属性END_PROP_MAP()		

  上面的代码,其实实现的是 IPersistStreamInit 接口,不过没有关系,因为 IPersistStreamInit 派生自 IPersistStream,实例化了派生类,自然就实例化了基类。在例子程序中,我只在桌面工具栏对象中添加了持续性属性,用来保存和初始化“命令行”。另外 COM_INTERFACE_ENTRY2(A,B)表示的含义是:如果想查询A接口的指针,则提供B接口指针来代替。为什么可以这样那?因为B接口派生自A接口,那么B接口的前几个函数必然就是A接口的函数了,自然B接口的地址其实和A接口的地址是一样的了。
  IObjectWithSite 是 IE 用来对插件进行管理和通讯用的一个接口。必须要实现这个接口的2个函数:SetSite() 和 GetSite()。当 IE 加载 band 对象和释放 band 对象的时候,都要调用 SetSite()函数,那么在这个函数里正好是写初始化和释放操作代码的地方:

STDMETHODIMP Cxxx::SetSite(IUnknown *pUnkSite){	if( NULL == pUnkSite )	// 释放 band 的时候	{		// 如果加载的时候,保存了一些接口		// 那么现在:释放它	}	else	// 加载 band 的时候	{		m_hwndParent = NULL;	// 装载 band 的父窗口(就是带有标题的那个框架窗口)		// 这个窗口的句柄,是调用 IUnknown::QueryInterface() 得到 IOleWindow		// 然后调用 IOleWindow::GetWindow() 而获得的。		CComQIPtr< IOleWindow, &IID_IOleWindow > spOleWindow(pUnkSite);		if( spOleWindow )	spOleWindow->GetWindow(&m_hwndParent);		if( !m_hwndParent )	return E_FAIL;				// 现在,正好是建立子窗口的时机。		// 注意,子窗口建立的时候,不要使用 WS_VISIBLE 属性		... ...		// 在例子程序中,用 CAxWindow 实现了一个能包容ActiveX的容器窗口(垂直浏览器栏)		// 在例子程序中,用 WIN API 函数 CreateWindow 实现了标准窗口(水平浏览器栏、工具栏)		// 在例子程序中,用 CWindowImpl 实现了一个包容窗口(桌面工具栏)		/*********************************************************/		   以下部分,根据 band 对象特有的功能,是可以选择实现的		**********************************************************/				// 如果子窗口实现了用户输入,那么必须实现 IInputObject 接口,		// 而该接口是被 IE 的 IInputObjectSite 调用的,因此在你的对象		// 中,应该保存 IInputObjectSite 的接口指针。		// 在类的头文件中,定义:		// CComQIPtr< IInputObjectSite, &IID_IInputObjectSite > m_spSite;		m_spSite = pUnkSite;	// 保存 IInputObjectSite 指针		if( !m_spSite )		return E_FAIL;		// 你需要控制 IE 的主框架吗?		// 那么在类的头文件中,定义:		// CComQIPtr< IWebBrowser2, &IID_IWebBrowser2 > m_spFrameWB;		// 然后,先取得 IServiceProvider,再取得 IWebBrowser2		CComQIPtr < IServiceProvider, &IID_IServiceProvider> spSP(pUnkSite);		if( !spSP )	return E_FAIL;		spSP->QueryService( SID_SWebBrowserApp, &m_spFrameWB );		if( !m_spFrameWB)	return E_FAIL;		// 如果你取得了 IE 主框架的 IWebBrowser2 指针		// 那么,当它发生了什么事情,你难道不想知道吗?		// 定义:CComPtr m_spCP;		CComQIPtr< IConnectionPointContainer,			&IID_IConnectionPointContainer> spCPC( m_spFrameWB );		if( spCPC )		{			spCPC->FindConnectionPoint( DIID_DWebBrowserEvents2, &m_spCP );			if( m_spCP )			{				m_spCP->Advise( reinterpret_cast< IDispatch * >( this ), &m_dwCookie );			}		}		// 咳~~~ 不说了,看源码去吧。这里能干的事情太多了... ...	}	return S_OK;}		

IDeskBand 是一个特殊的 band 对象接口,有一个方法函数:GetBarInfo();
IDockingWindow 是 IDeskBank 的基类,有3个方法函数:ShowDW()、CloseDW()、ResizeBorderDW();
IOleWindow 又是 IDockingWindow 的基类,有2个方法函数:GetWindow()、ContextSensitiveHelp();

  首先声明 IDeskBand ,然后要实现 IDeskBand 接口的共6个函数,这些函数比较简单,不同类型的 band 对象,其实现方法也都基本一致:

class ATL_NO_VTABLE Cxxx : 	......	public IDeskBand,	......{......BEGIN_COM_MAP(Cxxx)	......	COM_INTERFACE_ENTRY_IID(IID_IDeskBand, IDeskBand)	......END_COM_MAP()// IOleWindowSTDMETHODIMP Cxxx::GetWindow(HWND * phwnd){	// 取得 band 对象的窗口句柄	// m_hWnd 是建立窗口时候保存的	*phwnd = m_hWnd;		return S_OK;}STDMETHODIMP Cxxx::ContextSensitiveHelp(BOOL fEnterMode){	// 上下文帮助,参考 IContextMenu 接口	return E_NOTIMPL;}// IDockingWindowSTDMETHODIMP CVerticalBar::ShowDW(BOOL bShow){	// 显示或隐藏 band 窗口	if( m_hWnd )		::ShowWindow( m_hWnd, bShow ? SW_SHOW : SW_HIDE);	return S_OK;}STDMETHODIMP CVerticalBar::CloseDW(DWORD dwReserved){	// 销毁 band 窗口	if( ::IsWindow( m_hWnd ) )		::DestroyWindow( m_hWnd );	m_hWnd = NULL;    return S_OK;}STDMETHODIMP CVerticalBar::ResizeBorderDW(LPCRECT prcBorder, IUnknown* punkToolbarSite, BOOL fReserved){	// 当框架窗口的边框大小改变时	return E_NOTIMPL;}// IDeskBandSTDMETHODIMP CVerticalBar::GetBandInfo(DWORD dwBandID, DWORD dwViewMode,  DESKBANDINFO* pdbi){	         // 取得 band 的基本信息,你需要填写 pdbi 参数作为返回	if( NULL == pdbi )		return E_INVALIDARG;	// 如果将来需要调用 IOleCommandTarget::Exec() 则需要保存这2个参数	m_dwBandID = dwBandID;	m_dwViewMode = dwViewMode;	if(pdbi->dwMask & DBIM_MINSIZE)	{	// 最小尺寸		pdbi->ptMinSize.x = 10;		pdbi->ptMinSize.y = 10;	}	if(pdbi->dwMask & DBIM_MAXSIZE)	{	// 最大尺寸 (-1 表示 4G)		pdbi->ptMaxSize.x = -1;		pdbi->ptMaxSize.y = -1;	}	if(pdbi->dwMask & DBIM_INTEGRAL)	{		pdbi->ptIntegral.x = 1;		pdbi->ptIntegral.y = 1;	}	if(pdbi->dwMask & DBIM_ACTUAL)	{		pdbi->ptActual.x = 0;		pdbi->ptActual.y = 0;	}	if(pdbi->dwMask & DBIM_TITLE)	{	// 窗口标题		wcscpy(pdbi->wszTitle,L"窗口标题");	}	if(pdbi->dwMask & DBIM_MODEFLAGS)	{		pdbi->dwModeFlags = DBIMF_VARIABLEHEIGHT;	}	if(pdbi->dwMask & DBIM_BKCOLOR)	{	// 如果使用默认的背景色,则移除该标志		pdbi->dwMask &= ~DBIM_BKCOLOR;	}	return S_OK;}		

3.3 选择实现的 COM 接口
  有两个接口不是必须实现的,但也许很有用:IInputObject 和 IContextMenu。如果 band 对象需要接收用户的输入,那么必须实现 IInputObject 接口。IE 实现了 IInputObjectSite 接口,当容器中有多个输入窗口时,它调用 IInputObject 接口方法去负责管理用户的输入焦点。
在浏览器栏中需要实现3个函数:UIActivateIO()、HasFocusIO()、TranslateAcceleratorIO()。
当浏览器栏激活或失去活性的时候,IE 调用 UIActivateIO 函数,当激活的时候,浏览器栏一般调用 SetFocus 去设置它自己窗口的焦点。当 IE 需要判断哪个窗口有焦点的时候,它调用 HasFocusIO 。当浏览器栏的窗口或其子窗口有输入焦点时,则应返回 S_OK,否则返回 S_FALSE。TranslateAcceleratorIO 允许对象处理加速键,例子程序中没有实现,所以直接返回 S_FALSE。

STDMETHODIMP CExplorerBar::UIActivateIO(BOOL fActivate, LPMSG pMsg){    if(fActivate)        SetFocus(m_hWnd);    return S_OK;}STDMETHODIMP CExplorerBar::HasFocusIO(void){    if(m_bFocus)        return S_OK;    return S_FALSE;}STDMETHODIMP CExplorerBar::TranslateAcceleratorIO(LPMSG pMsg){    return S_FALSE;}      

  Band 对象能够通过包容器的 IOleCommandTarget::Exec() 调用执行命令。而 IOleCommandTarget 接口指针,则可以通过调用包容器的 IInputOjbectSite::QueryInterface(IID_IOleCommandTarget,…) 函数得到。CGID_DeskBand 是命令组,当一个 band 对象的 GetBandInfo 被调用的时候,包容器通过 dwBandID 参数指定一个 ID 给 band 对象,对象要保存住这个ID,以便调用 IOleCommandTarget::Exec()的时候使用。ID 的命令有:

  • DBID_BANDINFOCHANGED
    Band 的信息变化。设置参数 pvaIn 为 band ID, 该 ID 就是最近一次调用 GetBandInfo 所得到的值,容器会调用 band 对象的 GetBandInfo 函数来更新请求信息。
  • DBID_MAXIMIZEBAND
    最大化 band。设置参数 pvaIn 为 band ID,该 ID 就是最近一次调用 ?GetBandInfo ?所得到的值。
  • DBID_SHOWONLY
    打开或关闭容器中其它的 bands。 设置参数 pvaIn 为VT_UNKNOWN 类型,它可以是如下的值:
     
    描述
    pUnk band 对象的 IUnknown 指针,其它的桌面 bands 将被隐藏
    0 隐藏所有的桌面 bands
    1 显示所有的桌面 bands

  • DBID_PUSHCHEVRON
    在菜单项左边显示“v”的选择标志。容器发送一个 RB_PUSHCHEVRON 消息,当 band 对象接收到通知消息 RBN_CHEVRONPUSHED 提示它显示一个"v"的标志。设置 IOleCommandTarget::Exec 函数中 nCmdExecOpt 参数为 band ID,该 ID 是最近一次调用 GetBandInfo ?所得到的值,设置 IOleCommandTarget::Exec 函数中 pvaIn 参数为 VT_I4 类型,这是应用程序定义的一个值,它通过通知消息 RBN_CHEVRONPUSHED 中lAppValue 回传给 band 对象。

3.4 Band 对象注册
  Band 对象必须注册为一个 OLE 进程内的服务器,并且支持 apartment 线程公寓。注册表中默认键的值是表示菜单的文字。对于浏览器栏,它加到 IE 菜单的“查看\浏览器栏”中;对于工具栏 band ,它加到 IE 菜单的“查看\工具栏”中;对于桌面 band, 它加到系统任务栏的快捷菜单中。在菜单资源中,可以使用“&”指明加速键。

通常,一个基本的 band 对象的注册表项目是:

HKEY_CLASSES_ROOT
CLSID
{你的 band 对象的 CLSID}

  (Default) = 菜单的文字
  InProcServer32
   (Default) = DLL 的全路径文件名
   ThreadingModel= Apartment

工具栏 bands 还必须把它们的 CLSID 注册到 IE 的注册表中。

HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\Toolbar 下给出 CLSID 作为键名,而其键值是被忽略的。

HKEY_LOCAL_MACHINE
Software
Microsoft
Internet Explorer
Toolbar

  {你的 band 对象的 CLSID}

  还有几个可选的注册表项目(例子程序并不是这样实现的)。比如,你想让浏览器栏显示 HTML 的话,必须要如下设置注册表:

HKEY_CLASSES_ROOT
CLSID
{你的 Band 对象的 CLSID}
Instance
CLSID
  
(Default) = {4D5C8C2A-D075-11D0-B416-00C04FB90376}

同时,如果要指定一个本地的 HTML 文件,那么要如下设置:

HKEY_CLASSES_ROOT
CLSID
{你的 Band 对象的 CLSID}
Instance
InitPropertyBag
  
Url

  另外,还可以指定浏览器栏的宽和高,当然,它是依赖于这个栏是纵向还是横向的。其实这个项目无所谓,因为当用户调整了浏览器栏的大小后,会自动保存在注册表中的。

HKEY_CURRENT_USER
Software
Microsoft
Internet Explorer
Explorer Bars
{你的 Band 对象的 CLSID}
  
BarSize

  BarSize 键的类型必须是 REG_BINARY 类型,它有8个字节。左起前4个字节,是用16进制表示的像素宽度或高度,后4个字节保留,你应该设置为0。下面是一个可以在浏览器栏上显示 HTML 文件的全部注册表项目的例子,默认宽度为291(0×123)个像素点:

HKEY_CLASSES_ROOT
CLSID
{你的 Band 对象的 CLSID}

 (Default) = 菜单文字
 InProcServer32
  (Default) = DLL 的全路径文件名
  ThreadingModel= Apartment
Instance
CLSID

  (Default) = {4D5C8C2A-D075-11D0-B416-00C04FB90376}
InitPropertyBag
  Url= 你的 HTML 文件名

HKEY_CURRENT_USER
Software
Microsoft
Internet Explorer
Explorer Bars
{你的 Band 对象的 CLSID}

  BarSize= 23 01 00 00 00 00 00 00

  对于注册表的设置,用 ATL 实现其实是异常简单的。打开工程的 xxx.rgs 文件,并手工编辑一下就可以了。 下面这个文件源码,是例子程序中 IE 工具栏的注册表样式,HKLM 是需要手工添加的,因为它不使用组件类型方式注册。而对于其它类型的 band 对象只要在类声明中添加:

BEGIN_CATEGORY_MAP(Cxxx)			// 向注册表中注册 COM 类型	IMPLEMENTED_CATEGORY(CATID_InfoBand)	// 垂直样式的浏览器栏END_CATEGORY_MAP()		

IE 工具栏类型 band 对象的“.rgs”文件

HKCR	// 这个项目是 ATL 帮你生成的,你只要手工修改“菜单上的文字”就可以了{	Bands.ToolBar.1 = s ''ToolBar Class''	{		CLSID = s ''{ 你的 CLSID }''	}	Bands.ToolBar = s ''ToolBar Class''	{		CLSID = s ''{ 你的 CLSID }''		CurVer = s ''Bands.ToolBar.1''	}	NoRemove CLSID	{		ForceRemove { 你的 CLSID } = s ''用在菜单上的文字(&T)''		{			ProgID = s ''Bands.ToolBar.1''			VersionIndependentProgID = s ''Bands.ToolBar''			ForceRemove ''Programmable''			InprocServer32 = s ''%MODULE%''			{				val ThreadingModel = s ''Apartment''			}			''TypeLib'' = s ''{xxxx-xxxx-xxxxxxxxxxxxxxx}''		}	}}HKLM	// 这个项目是手工添加的IE工具栏所特有的{	Software	{		Microsoft		{			''Internet Explorer''			{				NoRemove Toolbar				{					ForceRemove val { 你的 CLSID } = s ''随便给个说明性文字串''				}			}		}	}}		

四、 ATL 实现
  下载代码后(VC 6.0 工程),请参照前面的说明仔细阅读,代码中也有一些关键点的注释。如果想运行,则可以用 regsvr32.exe 进行注册,然后打开 IE 浏览器或资源浏览器就可以看到效果了。如果想自己实践一下,可以按照如下的步骤构造工程:

4.1 建立一个 ATL DLL 工程
4.2 添加 New ATL Object…,选择 Internet Explorer Object,选这个类型的目的是让向导给我们添加 IObjectWithSite 的支持。如果你使用的是 .net 环境,则不要忘记选择支持这个接口。

4.3 输入对象名称,比如我想建立一个垂直的浏览器栏,不妨叫它 VerBar

4.4 线程模型必须选择 Apartment,接口类型的选择无所谓,看你想不想支持 IDispatch 接口功能了。在例子程序中的垂直浏览器栏中,由于想更简单的操纵 IE 和从 IE 中接受事件(连接点),选择 Dual 是必要的。聚合选项,你只要别选择 Only 就可以了。

4.5 展现你无穷的智慧,开始输入程序吧。如果是 方式编译,可能会出现一个连接错误,报告找不到_AtlAxCreateControl,那么你要在菜单 Project\Settings…\Link 中增加对 Atl.lib 的连接。或者使用 #pragma comment ( lib, "atl" )加入连接库。
4.6 如果想调试代码,在菜单 Project\Settings…\Debug 中输入 IE 的路径名称,比如:“C:\Program Files\Internet Explorer\IEXPLORE.EXE”,然后就可以跟踪断点调试了。 编译和调试桌面工具栏的 band 对象,是非常麻烦的,因为计算机启动时自动运行 Shell,而 Shell 就会加载活动的桌面对象。

五、结束语
好了,到这里,就到这里了。祝大家学习快乐^_^

0

免费软件套装


在 CB 上看到的……

办公

OpenOffice - office suite
PC Suite 602 - office suite
AbiWord – text editor
Atlantis Nova – text editor
Microsoft PowerPoint Viewer - power point files viewer
Adobe Reader – pdf reader
Foxit PDF Reader – pdf reader
PDFCreator – create pdf documents
Doc Convertor - document convertor
Convert – unit convertor
Converber – unit convertor
Sunbird – calendar/organizer
EssentialPIM Free – calendar/organizer
PhraseExpress – speed up your writing
ATnotes – create notes on the desktop

解压缩

7-Zip - compression program
IZArc - compression program
TugZIP - compression program
CabPack – compression program
Universal Extractor – extract files from any type of archive

互联网

Firefox browser
Internet Explorer- web browser
Maxthon – web browser
Opera – web browser
Avant Browser – web browser
Thunderbird – email client
PopTray – check for emails
Free Download Manager – download manager
FlashGet - download manager
WellGet – download manager
Download Master – download manager
WGET – commandline download manager
HTTrack – offline browser
WebReaper – offline browser
Yeah Reader - RSS reader
GreatNews - RSS reader
RSSOwl – RSS reader

P2P

µTorrent – torrent client
Azureus – torrent client
BitComet – torrent client
ABC – torrent client
BitTornado – torrent client
eMule – p2p client
SoulSeek – p2p client
Shareaza – p2p client
DC++ – Direct Connect network client
PeerGuardian – IP blocker

聊天

Miranda – chat client
MSN Messenger – chat client
Yahoo Messenger – chat client
QIP – chat client
Gaim – chat client
JAJC – chat client
HydraIRC – IRC client
Talkative IRC – IRC client
IceChat – IRC client
Skype – VOIP client
Google Talk - VOIP client
VoipStunt – VOIP client
Gizmo – VOIP client
Wengo – VOIP client

安全

AVG Free – antivirus
Avast Home Free – antivirus
AntiVir PersonalEdition – antivirus
BitDefender Free – antivirus
ClamWin – antivirus
CyberDifender - Internet Security Suite
Ad-aware – anti-spyware
Spybot: Search & Destroy – anti-spyware
Windows Defender – anti-spyware
SpywareBlaster - anti-spyware
Spyware Terminator – anti-spyware
Tootkit Reveaker - rootkit detection utility
Winpooch - system protection
HiJack Free – system protection
HighJackThis – hijackers detector and remover
Kerio Personal Firewall – firewall
Sygate Personal Firewall - firewall
ZoneAlarm - firewall
AxCrypt – file encryption
Simple File Shredder – securely delete files
PuTTy - SSH client
KeePass – password manager
LockNote – password manager
nPassword – password manager
Microsoft Baseline Security Analyzer – identify security misconfigurations

网络

Hamachi – VPN client
RealVNC – remote control
UltraVNC – remote control
Ethereal – local area network administration
The Dude – network administration
Wireshark – network administration
Angry IP Scanner – IP scanner
IP-Tools - IP scanner
Free Port Scanner – IP scanner
NetMeter – network bandwidth monitoring

服务器

FileZilla – FTP client
FileZilla Server – FTP
EFTP – FTP client/server
XAMPP – integrated server package of Apache, mySQL, and Perl
WAMP – Apache, PHP5 and MySQL server

音频

Foobar2000 – audio player
WinAmp – audio player
1by1 – audio player
JetAudio – audio player
XMPlay – audio player
Xion – audio player
Apollo – audio player
MediaMonkey – music organizer
The GodFather – music organizer
dBpowerAMP – audio converter
Audacity – audio converter
WavePad – audio converter
Kristal Audio Engine – audio editor
Exact Audio Copy – CD ripper
Audiograbber – CD ripper
CDex – CD ripper
Mp3 Tag Tools – tag editor
Mp3tag – tag editor
Taggin’ MP3 – tag editor
Monkey’s Audio – APE compressor/decompressor
mpTrim - mp3 editor
WavTrim - wave editor
EncSpot Basic – analyse mp3 files

视频

Windows Media Player – audio/video player
VLC – video player
Media Player Classic – video player
MV2Player – video player
CrystalPlayer 1.95 – video player
Zoom Player – video player
GOM Player – video player
viPlay – video player
DSPlayer – video player
VirtualDub – video editor
CamStudio – video screen recording
AviSplit – Avi splitter
Video mp3 Extractor – rip audio from video files
Free iPod Converter – convert all popular video formats to iPod video
MediaPortal – turning your PCinto a Media Center
The FilmMachine

图像

Gimp – image editor
PhotoFiltre – image editor
Paint.net – image editor
ArtRage - image editor
Artweaver – image editor
IrfanView - image viewer
Picasa - image viewer
XnView – image viewer
FastStone Image Viewer - image viewer
FuturixImager - image viewer
Easy Thumbnails – create thumbnails from images
JoJoThumb – create thumbnails from images
iWebAlbum - create web photo albums
JAlbum – create web photo albums
3D Box Shot Maker - design quality box shot
FastStone Capture - screen capture
WinSnap - screen capture

3D

Blender3D – 3D renderer
3Delight Free – 3D renderer
SketchUp – 3D modeling
Maya Learning Edition – 3D modeling

AutoIt – task automation
SciTE4AutoIt3 - text editor for AutoIt
AutoHotkey - task automation
PHP Designer – PHP editor
Notepad++ – text editor
ConTEXT Editor – text editor
PSPad – text editor
FoxEditor - text editor
Crimson Editor - source code editor
Elfima Notepad - text editor
Notepad2 - text editor
Nvu – HTML editor
Alleycode - HTML editor
BlockNote - web page editor
Weaverslave – web page editor

CD/DVD

DeepBurner – CD/DVD burner
CDBurner XP Pro – CD/DVD burner
BurnAtOnce – CD/DVD burner
Express Burn – CD/DVD burner
Zilla CD-DVD Rip’n’Burn – CD/DVD
刻录
ImgBurn – ISO, BIN burner
Daemon tools – virtual CD/DVD
DVD Decrypter – DVD ripper
DVD Shrink – DVD ripper
Nero CD-DVD Speed - CD/DVD info and quality test
解码

GSpot - codec information
AC3Filter – audio codec
Xvid – video codec
QuickTime Alternative – video codec
Real Alternative – video codec
K-Lite Codec Pack – all codecs

系统工具

CCleaner – system cleaner
xp-AntiSpy – OS setup
jv16 Powertools – system utilities
XP SysPad – system monitoring utility
What’s Running – process guard
Registrar Lite – registry editor
WinIPConfig – replacement for “ipconfig.exe” and “route.exe”
Unlocker – file eraser
Eraser – secure file eraser
Undelete Plus – file recovery
freeCommander – file manager
ExplorerXP - file manager
Duplicate File Finder – find all duplicate files
Ant Renamer – file renaming
ReNamer – file renaming
Icons From File – icos extractor
Chaos MD5 – MD5 generator
HashTab - MD5, SHA1 and CRC-32 file hashes
Rainlendar Lite – desktop calendar
Weather Watcher – weather firecast
Subtitle Workshop – subtitles editor
Ant Movie Catalog – movie organizer
Disclib – CD organizer
Dexpot – virtual desktops
DriveImage XML – create partition images
MozBackup – backup and restore bookmarks, etc.
SyncBack – system backup
Atomic Cock Sync – syncronize your clock
Citrus Alarm Clock – alarm clock
TaskSwitchXP – Alt-Tab replacement
Launchy - application launcher
allSnap – make all snap
Sysinternals Tools – various system tools
StrokeIt - mouse gestures
Net Profiles – create profiles of your network settings
ResourceHacker – view, modify, rename, add, delete
Java Runtime Environment – java for Windows

UI设计

RocketDock - application launcher
AveDesk – desktop enhancer
IconPhile - customize windows’s system icons
CursorXP Free – change mouse cursors
MacSound – volume control
LClock - Windows Longhorn clock
Y’z Dock – application launcher
Y’z Shadow – shadow effect to the windows
Y’z Toolbar – change the toolbar icons in Explorer and Internet Explorer
Taskbar Shuffle – rearrange the programs on the taskbar by dragging
Visual Task Tips – thumbnail preview image for each task in the taskbar
Badges - put badges on any folder or file
Folderico - change icons of the folders
Folder Marker – mark your folders
Folder2MyPC – add favourite locations to My Computer
Microsoft TweakUI – system settings
BricoPacks packs
ShellPacks – shell packs
Tango Shell Patcher – shell patcher
XPize – GUI enhancer
Vista Transformation Pack - complete visual style
Vista Sound Scheme – Windows Vista sound scheme
Royale Theme - visual style

硬件检测

CPU-Z - cpu information
CrystalCPUID – cpu information
Central Brain Identifier – cpu information
Everest – system information
SiSoft Sandra - system information
SpeedFan - hardware monitor
Memtest86 – memory test
PowerMax – HDD test
3Dmark 06 - 3D game performance benchmark
Aquamark - performance benchmark
rthdribl – 3D benchmark
Fraps - 3D benchmark, fps viewer and screen recorder
Prime 95 - cpu benchmarking
SuperPI - cpu benchmarking
CPU Rightmark - cpu overclock
Core Temp - cpu temperature
ATiTool - video overclock
ATI Tray Tools – Radeon tweaker
aTuner - GeForce and Radeontweaker
RivaTuner – video overclock
Nokia Monitor Test - monitor adjustmets
UDPixel – fix dead pixels

游戏

123 Free Solitaire - solitaire games collection
Arcade Pack - classic arcade games
Live For Speed – online racing simulator
Enigma – puzzle game
Freeciv – multiplayer strategy game
Tux Racer – race down steep, snow-covered mountains

教育

SpeQ Mathematics - mathematics program
Dia – diagram creation program
Google Earth – explore the world
NASA World Wind – 3D virtual globe
Celestia – explore the space
Stellarium – planetarium

杂类

nLite – Build your own custom Windows disk.
VirtualPC – create virtual machines
grabMotion - webcam capture
iDailyDiary – simple page-for-a-day diary
Pivot Stickfigure Animator – create stick-figure animations
Wink – create presentations
Scribus – professional page layout
FreeMind – midn mapping software
Windows Live Writer – WYSIWYG authoring

墙纸

Michael Swanson - 1920 x 1200; 1600 x 1200; amazing wallpapers
Mikhail Arkhipov - 1920 x 1200; 1600 x 1200; amazing wallpapers

0

组件注册命令 Regsvr32 的各种用法解析


Windows系统提供的Regsvr32命令也许很多朋友都见过可能还不知道怎么用,它可是一个很实用的功能。

一、能够帮你轻松修复IE浏览器
很多经常上网的朋友都有过这样的遭遇:IE不能打开新的窗口,用鼠标点击超链接也没有任何反应。这时重装IE一般能解决问题。其实不必这么麻烦,使用Regsvr32命令就可以轻松搞定。

在“开始→运行”中键入“regsvr32 actxprxy.dll”命令,点击“确定”按钮,这时会弹出一个信息对话框“DllRegisterServer in actxprxy.dll succeeded”,点击“确定”;然后再在“开始→运行”中键入“regsvr32 shdocvw.dll”命令,单击“确定”即可。重新启动后IE已经被轻松修复了。

二、解决Windows无法在线升级的问题
Windows的漏洞很多,每隔一段时间就需要使用“ Update”升级程序进行在线升级,不过“ Update”经常出现无法使用的情况,这时,我们可以使用Regsvr32来解决这个问题。

在“开始→运行”中键入“regsvr32 wupdinfo.dll”,点击“确定”按钮,这样在系统中就重新注册了“Windows Update”组件,重新启动后问题已经解决。

三、防范网络脚本病毒有新招
网络脚本病毒嵌在网页中,上网时在不知不觉中机器就会感染上这种病毒。笔者认为单纯使用杀毒软件并不能有效地防范这些脚本病毒,必须从病毒传播的机理入手。网络脚本病毒的复制、传播都离不开FSO对象(File System Object,文件系统对象),因此禁用FSO对象就能有效地控制脚本病毒的传播。操作方法很简单:

在“开始→运行”中键入“regsvr32 /u scrrun.dll”就可以禁用FSO对象;如果需要使用FSO对象,键入“regsvr32 scrrun.dll”命令即可。

四、卸载Win XP自带的“鸡肋”功能
Win XP以功能强大而著称,但有些功能却常常令人有“鸡肋”之感,比如Win XP自带的ZIP功能和图片预览功能,不仅占用了系统资源,功能也远不如第三方软件强大。其实用Regsvr32命令可以很容易地卸载这些功能。

在“开始→运行”中键入“regsvr32 /u zipfldr.dll”,单击“确定”按钮,弹出卸载成功信息框后就完成了ZIP功能的卸载;要恢复ZIP功能,键入“regsvr32 zipfldr.dll”即可。同样,卸载图片预览功能也很简单,在“开始→运行”中键入“regsvr32 /u thumbvw.dll”即可;如果要恢复该功能,只须键入“regsvr32 thumbvw.dll”。

五、让WMP播放器支持RM格式
很多朋友喜欢用Windows Media Player(以下简称WMP)播放器,但是它不支持RM格式,难道非得安装其他播放软件吗?笔者有办法。

以Win XP为例,首先下载一个RM格式插件,解压缩后得到两个文件夹:Release(用于Windows 9x)和Release Unicode (用于Windows 2000/XP);将Release Unicode文件夹下的RealMediaSplitter.ax文件拷贝到“系统盘符\\WINDOWS\\System32\\”目录下;在“开始→运行”中键入“regsvr32 RealMediaSplitter.ax”,点击“确定”即可。接着下载解码器,如Real Alternative,安装后就能用WMP播放RM格式的影音文件了。

RM格式插件下载地址:http://www.fyrose.com/realmediasplitter_20030729.zip

RM格式解码器下载地址:http://www.fyrose.com/realalt111.exe

你知道吗?Regsvr32命令
Regsvr 32命令是Windows中控件文件(如扩展名为DLL、OCX、CPL的文件)的注册和反注册工具。

格式:regsvr32 [/s] [/n] [/i[:cmdline]] DLLname

使用参数——–解除服务器注册
使用参数[/s]——–无声;不显示消息框
使用参数———调用DllInstall,给其传递一个可选[cmdline];跟/u参数一起使用时卸载DLL。
使用参数[/n]——–不用调用DLLRegisterServer。这个参数必须跟/i一起使用。

简单实例
要手工注册“E:\CPCW.dll”,只需在“开始→运行”中键入“Regsvr32 E:\CPCW.dll”,单击“确定”按钮后会弹出提示信息“DllRegisterServer in CPCW.dll succeeded”,说明组件注册成功;如果要卸载此组件,在“开始→运行”中键入“Regsvr32 /u E:\CPCW.dll”即可。

实例1:IE无法打开新窗口

regsvr32 actxprxy.dll
regsvr32 shdocvw.dll

重启后如果还不能解决

regsvr32 mshtml.dll
regsvr32 urlmon.dll
regsvr32 msjava.dll
regsvr32 browseui.dll
regsvr32 oleaut32.dll
regsvr32 32.dll

实例2:IE无法保存HTML格式文件

regsvr32 inetcomm.dll

实例3:MSN无法登陆

regsvr32 softpub.dll

实例4:windows默认的文件关联混乱

regsvr32 /i shdocvw.dll
regsvr32 /i shell.dll
regsvr32 /i shdoc401.dll

实例5:Window 2003中无法播放MP3

regsvr32 i3codeca.acm
regsvr32 i3codecx.ax

实例6:Windows添加/删除程序无法启动

regsvr32 mshtml.dll
regsvr32 /i shdocvw.dll
regsvr32 /i shell.dll

实例7 Windows搜索功能故障

regsvr32 urlmon.dll

实例8:禁止系统对媒体文件进行预览

regsvr32 /u shmedia.dll

恢复可用

regsvr32 shmedia.dll

实例9:卸载Win XP自带的zip功能

regsvr32 /u zipfldr.dll

实例10:禁用FSO对象

regsvr32 /u scrrun.dll

0

FTP命令大全


FTP命令非常使用,尤其是在UNIX系统下FTP命令是Internet用户使用最频繁的命令之一,不论是在DOS还是UNIX操作系统下使用
FTP,都会遇到大量的FTP内部命令。熟悉并灵活应用FTP的内部命令,可以大大方便使用者,
并收到事半功倍之效。

  FTP的命令行格式为: ftp -v -d -i -n -g [主机名] ,其中
  -v 显示远程服务器的所有响应信息;
  -d 使用调试方式;
  -i 限制ftp的自动登录,即不使用;
  -n etrc文件;
  -g 取消全局文件名。

  ftp使用的内部命令如下(中括号表示可选项):
  1. ![cmd[args]]:在本地机中执行交互shell,exit回到ftp环境,如:!ls*.zip。
  2. $ macro-ame[args]:执行宏定义macro-name。
  3. account[password]:提供登录远程系统成功后访问系统资源所需的补充口令。
  4. append local-file[remote-file]:将本地文件追加到远程系统主机,若未指定远程系统文件名,则使用本地文件名。
  5. ascii:使用ascii类型传输方式。
  6. bell:每个命令执行完毕后计算机响铃一次。
  7. bin:使用二进制文件传输方式。
  8. bye:退出ftp会话过程。
  9. case:在使用mget时,将远程主机文件名中的大写转为小写字母。
  10. cd remote-dir:进入远程主机目录。
  11. cdup:进入远程主机目录的父目录。
  12. chmod mode file-name:将远程主机文件file-name的存取方式设置为mode,如: chmod 777 a.out 。
  13. close:中断与远程服务器的ftp会话(与open对应)。
  14. cr:使用asscii方式传输文件时,将回车换行转换为回行。
  15. delete remote-file:删除远程主机文件。
  16. [debug-value]:设置调试方式, 显示发送至远程主机的每条命令,如: deb up 3,若设为0,表示取消debug。
  17. dir[remote-dir][local-file]:显示远程主机目录,并将结果存入本地文件local-file。
  18. disconnection:同close。
  19. form format:将文件传输方式设置为format,缺省为file方式。
  20. get remote-file[local-file]: 将远程主机的文件remote-file传至本地硬盘的local-file。
  21. glob:设置mdelete,mget,mput的文件名扩展,缺省时不扩展文件名,同命令行的-g参数。
  22. hash:每传输1024字节,显示一个hash符号(#)。
  23. help[cmd]:显示ftp内部命令cmd的帮助信息,如:help get。
  24. idle[seconds]:将远程服务器的休眠计时器设为[seconds]秒。
  25. image:设置二进制传输方式(同binary)。
  26. lcd[dir]:将本地工作目录切换至dir。
  27. ls[remote-dir][local-file]:显示远程目录remote-dir, 并存入本地文件local-file。
  28. macdef macro-name:定义一个宏,遇到macdef下的空行时,宏定义结束。
  29. mdelete[remote-file]:删除远程主机文件。
  30. mdir remote-files local-file:与dir类似,但可指定多个远程文件,如: mdir *.o.*.zipoutfile 。
  31. mget remote-files:传输多个远程文件。
  32. mkdir dir-name:在远程主机中建一目录。
  33. mls remote-file local-file:同nlist,但可指定多个文件名。
  34. mode[modename]:将文件传输方式设置为modename, 缺省为stream方式。
  35. modtime file-name:显示远程主机文件的最后修改时间。
  36. mput local-file:将多个文件传输至远程主机。
  37. newer file-name: 如果远程机中file-name的修改时间比本地硬盘同名文件的时间更近,则重传该文件。
  38. nlist[remote-dir][local-file]:显示远程主机目录的文件清单,并存入本地硬盘的local-file。
  39. nmap[inpattern outpattern]:设置文件名映射机制, 使得文件传输时,文件中的某些字符相互转换,如:nmap $1.$2.$3[$1,$2].[$2,$3],则传输文件a1.a2.a3时,文件名变为a1,a2。该命令特别适用于远程主机为非UNIX机的情况。
  40. ntrans[inchars[outchars]]:设置文件名字符的翻译机制,如ntrans1R,则文件名LLL将变为RRR。
  41. open host[port]:建立指定ftp服务器连接,可指定连接端口。
  42. passive:进入被动传输方式。
  43. prompt:设置多个文件传输时的交互提示。
  44. proxy ftp-cmd:在次要控制连接中,执行一条ftp命令,该命令允许连接两个ftp服务器,以在两个服务器间传输文件。第一条ftp命令必须为open,以首先建立两个服务器间的连接。
  45. put local-file[remote-file]:将本地文件local-file传送至远程主机。
  46. pwd:显示远程主机的当前工作目录。
  47. quit:同bye,退出ftp会话。
  48. quote arg1,arg2…:将参数逐字发至远程ftp服务器,如:quote syst。
  49. recv remote-file[local-file]:同get。
  50. reget remote-file[local-file]:类似于get,但若local-file存在,则从上次传输中断处续传。
  51. rhelp[cmd-name]:请求获得远程主机的帮助。
  52. rstatus[file-name]:若未指定文件名,则显示远程主机的状态,否则显示文件状态。
  53. rename[from][to]:更改远程主机文件名。
  54. reset:清除回答队列。
  55. restart marker:从指定的标志marker处,重新开始get或put,如:restart 130。
  56. rmdir dir-name:删除远程主机目录。
  57. runique:设置文件名唯一性存储。
  58. send local-file[remote-file]:同put。
  59. sendport:设置PORT命令的使用。
  60. site arg1,arg2…:将参数作为SITE命令逐字发送至远程ftp主机。
  61. size file-name:显示远程主机文件大小,如:site idle 7200。
  62. status:显示当前ftp状态。
  63. struct[struct-name]:将文件传输结构设置为struct-name,缺省时使用stream结构。
  64. sunique:将远程主机文件名存储设置为唯一(与runique对应)。
  65. system:显示远程主机的操作系统类型。
  66. tenex:将文件传输类型设置为TENEX机的所需的类型。
  67. tick:设置传输时的字节计数器。
  68. trace:设置包跟踪。
  69. type[type-name]:设置文件传输类型为type-name,缺省为ascii,如:type binary,设置二进制传输方式。
  70. umask[newmask]:将远程服务器的缺省umask设置为newmask,如:umask 3。
  71. user user-name[password][account]:向远程主机表明自己的身份,需要口令时,必须输入口令,如:user anonymous my@email。
  72. verbose:同命令行的-v参数,即设置详尽报告方式,ftp服务器的所有响应都将显示给用户,缺省为on。
  73. ?[cmd]:同help。

Previous Page

Random Posts Recent Comments

  • 女友糖尿病害我蛀牙 Says:

    汗一个…...

  • Htj06 Says:

    zhenyouchuangyi...

  • 电商圈 Says:

    试图该怎么建立啊,,怎在程序中是吸纳...

  • edward Says:

    看得人心旷神怡,好文,情不自禁的顶一下...

  • Daniel Says:

    我也在处理这个问题,没有找到好的方法。我用了楼上兄弟的方法,还是可以的。不知道您找到好的方法了吗、我暂时楼上兄弟的方法。...

  • 卡,卡 Says:

    弱弱问一句:博主,你博客的模板这样设计pv高吗?...

  • 站长工具 Says:

    博主,兔年快乐!...

  • health Says:

    great post!!I hope I can read more in your website....

  • pdu Says:

    好博文,支持分享...

  • 站长工具 Says:

    博主的文章很不错,我是站长工具-站长精灵的作者,一款专业的SEO工具软件(可以帮您提高博客的流量),想跟您交换个链接,不知可否...

Tag Cloud

arm audio blog brew cache class debug flash google html j2me java javascript Joke linux lua mobile mtk php python ror ruby server shell stream unix web windows 优化 动态加载 女人 女生 平台 开发 手机 技术 流媒体 测试 漫画 生活 男人 男生 缓存 芯片