0

修改PE文件结构


转至http://www.xfocus.net

在windows 9x、NT、2000下,所有的可执行文件都是基于Microsoft设计的一种新的文件格式Portable Executable File Format(可移植的执行体),即PE格式。有一些时候,我们需要对这些可执行文件进行修改,下面文字试图详细的描述PE文件的格式及对PE格式文件的修改。
1、PE文件框架构成
DOS MZ header
DOS stub
PE header
Section table
Section 1
Section 2
Section …
Section n
上表是PE文件结构的总体层次分布。所有 PE文件(甚至32位的 DLLs) 必须以一个简单的 DOS MZ header 开始,在偏移0处有DOS下可执行文件的“MZ标志”,有了它,一旦程序在DOS下执行,DOS就能识别出这是有效的执行体,然后运行紧随 MZ header 之后的 DOS stub。DOS stub实际上是个有效的EXE,在不支持 PE文件格式的操作系统中,它将简单显示一个错误提示,类似于字符串 " This program cannot run in DOS mode " 或者程序员可根据自己的意图实现完整的 DOS代码。通常DOS stub由汇编器/编译器自动生成,对我们的用处不是很大,它简单调用中断21h服务9来显示字符串"This program cannot run in DOS mode"。
紧接着 DOS stub 的是 PE header。 PE header 是PE相关结构 IMAGE_NT_HEADERS 的简称,其中包含了许多PE装载器用到的重要域。可执行文件在支持PE文件结构的操作系统中执行时,PE装载器将从 DOS MZ header的偏移3CH处找到 PE header 的起始偏移量。因而跳过了 DOS stub 直接定位到真正的文件头 PE header。
PE文件的真正内容划分成块,称之为sections(节)。每节是一块拥有共同属性的数据,比如“.text”节等,那么,每一节的内容都是什么呢?实际上PE格式的文件把具有相同属性的内容放入同一个节中,而不必关心类似“.text”、“.data”的命名,其命名只是为了便于识别,所有,我们如果对PE格式的文件进行修改,理论上讲可以写入任何一个节内,并调整此节的属性就可以了。
PE header 接下来的数组结构 section table(节表)。 每个结构包含对应节的属性、文件偏移量、虚拟偏移量等。如果PE文件里有5个节,那么此结构数组内就有5个成员。
以上就是PE文件格式的物理分布,下面将总结一下装载一PE文件的主要步骤:
1、    PE文件被执行,PE装载器检查 DOS MZ header 里的 PE header 偏移量。如果找到,则跳转到 PE header。
2、PE装载器检查 PE header 的有效性。如果有效,就跳转到PE header的尾部。
3、紧跟 PE header 的是节表。PE装载器读取其中的节信息,并采用文件映射方法将这些节映射到内存,同时付上节表里指定的节属性。
4、PE文件映射入内存后,PE装载器将处理PE文件中类似 import table(引入表)逻辑部分。
上述步骤是一些前辈分析的结果简述。
2、PE文件头概述
我们可以在winnt.h这个文件中找到关于PE文件头的定义:
typedef struct _IMAGE_NT_HEADERS {
DWORD Signature;                
//PE文件头标志 :“PE\0\0”。在开始DOS header的偏移3CH处所指向的地址开始
IMAGE_FILE_HEADER FileHeader;        //PE文件物理分布的信息
IMAGE_OPTIONAL_HEADER32 OptionalHeader;    //PE文件逻辑分布的信息
} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;

typedef struct _IMAGE_FILE_HEADER {
WORD    Machine;            //该文件运行所需要的CPU,对于Intel平台是14Ch
WORD    NumberOfSections;        //文件的节数目
DWORD   TimeDateStamp;        //文件创建日期和时间
DWORD   PointerToSymbolTable;    //用于调试
DWORD   NumberOfSymbols;        //符号表中符号个数
WORD    SizeOfOptionalHeader;    //OptionalHeader 结构大小
WORD    Characteristics;        //文件信息标记,区分文件是exe还是dll
} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;

typedef struct _IMAGE_OPTIONAL_HEADER {
WORD    Magic;            //标志字(总是010bh)
BYTE    MajorLinkerVersion;        //连接器版本号
BYTE    MinorLinkerVersion;        //
DWORD   SizeOfCode;            //代码段大小
DWORD   SizeOfInitializedData;    //已初始化数据块大小
DWORD   SizeOfUninitializedData;    //未初始化数据块大小
DWORD   AddressOfEntryPoint;    //PE装载器准备运行的PE文件的第一个指令的RVA,若要改变整个执行的流程,可以将该值指定到新的RVA,这样新RVA处的指令首先被执行。(许多文章都有介绍RVA,请去了解)
DWORD   BaseOfCode;            //代码段起始RVA
DWORD   BaseOfData;            //数据段起始RVA
DWORD   ImageBase;            //PE文件的装载地址
DWORD   SectionAlignment;        //块对齐
DWORD   FileAlignment;        //文件块对齐
WORD    MajorOperatingSystemVersion;//所需操作系统版本号
WORD    MinorOperatingSystemVersion;//
WORD    MajorImageVersion;        //用户自定义版本号
WORD    MinorImageVersion;        //
WORD    MajorSubsystemVersion;    //win32子系统版本。若PE文件是专门为Win32设计的
WORD    MinorSubsystemVersion;    //该子系统版本必定是4.0否则对话框不会有3维立体感
DWORD   Win32VersionValue;        //保留
DWORD   SizeOfImage;            //内存中整个PE映像体的尺寸
DWORD   SizeOfHeaders;        //所有头+节表的大小
DWORD   CheckSum;            //校验和
WORD    Subsystem;            //NT用来识别PE文件属于哪个子系统
WORD    DllCharacteristics;        //
DWORD   SizeOfStackReserve;        //
DWORD   SizeOfStackCommit;        //
DWORD   SizeOfHeapReserve;        //
DWORD   SizeOfHeapCommit;        //
DWORD   LoaderFlags;            //
DWORD   NumberOfRvaAndSizes;    //
IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
//IMAGE_DATA_DIRECTORY 结构数组。每个结构给出一个重要数据结构的RVA,比如引入地址表等
} IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;

typedef struct _IMAGE_DATA_DIRECTORY {
DWORD   VirtualAddress;        //表的RVA地址
DWORD   Size;                //大小
} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;

PE文件头后是节表,在winnt.h下如下定义
typedef struct _IMAGE_SECTION_HEADER {
BYTE    Name[IMAGE_SIZEOF_SHORT_NAME];//节表名称,如“.text”
union {
    DWORD   PhysicalAddress;    //物理地址            
    DWORD   VirtualSize;        //真实长度
} Misc;
DWORD   VirtualAddress;        //RVA
DWORD   SizeOfRawData;        //物理长度
DWORD   PointerToRawData;        //节基于文件的偏移量
DWORD   PointerToRelocations;    //重定位的偏移
DWORD   PointerToLinenumbers;    //行号表的偏移
WORD    NumberOfRelocations;    //重定位项数目
WORD    NumberOfLinenumbers;    //行号表的数目
DWORD   Characteristics;        //节属性
} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;

以上结构就是在winnt.h中关于PE文件头的定义,如何我们用C/C++来进行PE可执行文件操作,就要用到上面的所有结构,它详细的描述了PE文件头的结构。

3、修改PE可执行文件
现在让我们把一段代码写入任何一个PE格式的可执行文件,代码如下:
– test.asm –
.386p
.model flat, stdcall
option casemap:none

include \masm32\include\.inc
include \masm32\include\user32.inc
includelib \masm32\lib\user32.lib

.code

start:
    INVOKE MessageBoxA,0,0,0,MB_ICONINFORMATION or MB_OK
    ret
end start

以上代码只显示一个MessageBox框,编译后得到二进制代码如下:
unsigned char writeline[18]={
0x6a,0×40,0x6a,0×0,0x6a,0×0,0x6a,0×0,0xe8,0×01,0×0,0×0,0×0,0xe9,0×0,0×0,0×0,0×0
};

好,现在让我们看看该把这些代码写到那。现在用Tdump.exe显示一个PE格式得可执行文件信息,可以发现如下描述:
Object table:
#   Name      VirtSize    RVA     PhysSize  Phys off  Flags  
–  ——–  ——–  ——–  ——–  ——–  ——–
01  .text     0000CCC0  00001000  0000CE00  00000600  60000020 [CER]
02  .data     00004628  0000E000  00002C00  0000D400  C0000040 [IRW]
03  .rsrc     000003C8  00013000  00000400  00010000  40000040 [IR]

Key to section flags:
  C – contains code
  E – executable
  I – contains initialized data
  R – readable
  W – writeable

上面描述此文件中存在3个段及每个段得信息,实际上我们的代码可以写入任何一个段,这里我选择“.text”段。

用如下代码得到一个PE格式可执行文件的头信息:

//writePE.cpp

#include <windows.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <time.h>
#include <SYS\STAT.H>

unsigned char writeline[18]={
0x6a,0×40,0x6a,0×0,0x6a,0×0,0x6a,0×0,0xe8,0×01,0×0,0×0,0×0,0xe9,0×0,0×0,0×0,0×0
};

DWORD space;
DWORD entryaddress;
DWORD entrywrite;
DWORD progRAV;
DWORD oldentryaddress;
DWORD newentryaddress;
DWORD codeoffset;
DWORD peaddress;
DWORD flagaddress;
DWORD flags;

DWORD virtsize;
DWORD physaddress;
DWORD physsize;
DWORD MessageBoxAadaddress;

int main(int argc,char * * argv)
{
HANDLE hFile, hMapping;
void *basepointer;
FILETIME * Createtime;
FILETIME * Accesstime;
FILETIME * Writetime;
Createtime = new FILETIME;
Accesstime = new FILETIME;
Writetime = new FILETIME;

if ((hFile = CreateFile(argv[1], GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0)) == INVALID_HANDLE_VALUE)//打开要修改的文件
{
puts("(could not open)");
return EXIT_FAILURE;
}
if(!GetFileTime(hFile,Createtime,Accesstime,Writetime))
{
printf("\nerror getfiletime: %d\n",GetLastError());
}
//得到要修改文件的创建、修改等时间
if (!(hMapping = CreateFileMapping(hFile, 0, PAGE_READONLY | SEC_COMMIT, 0, 0, 0)))
{
puts("(mapping failed)");
CloseHandle(hFile);
return EXIT_FAILURE;
}
if (!(basepointer = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0)))
{
puts("(view failed)");
CloseHandle(hMapping);
CloseHandle(hFile);
return EXIT_FAILURE;
}
//把文件头映象存入baseointer
CloseHandle(hMapping);
CloseHandle(hFile);
map_exe(basepointer);//得到相关地址
UnmapViewOfFile(basepointer);
printaddress();
printf("\n\n");
if(space<50)
{
printf("\n空隙太小,数据不能写入.\n");
}
else
{
writefile();//写文件
}

if ((hFile = CreateFile(argv[1], GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0)) == INVALID_HANDLE_VALUE)
{
puts("(could not open)");
return EXIT_FAILURE;
}

if(!SetFileTime(hFile,Createtime,Accesstime,Writetime))
{
printf("error settime : %d\n",GetLastError());
}
//恢复修改后文件的建立时间等
delete Createtime;
delete Accesstime;
delete Writetime;
CloseHandle(hFile);
return 0;
}

void map_exe(const void *base)
{
IMAGE_DOS_HEADER * dos_head;
dos_head =(IMAGE_DOS_HEADER *)base;
#include <pshpack1.h>
typedef struct PE_HEADER_MAP
{
DWORD signature;
IMAGE_FILE_HEADER _head;
IMAGE_OPTIONAL_HEADER opt_head;
IMAGE_SECTION_HEADER section_header[];
} peHeader;
#include <poppack.h>

if (dos_head->e_magic != IMAGE_DOS_SIGNATURE)
{
puts("unknown type of file");
return;
}

peHeader * header;
header = (peHeader *)((char *)dos_head + dos_head->e_lfanew);//得到PE文件头
if (IsBadReadPtr(header, sizeof(*header))
{
puts("(no PE header, probably DOS executable)");
return;
}

DWORD mods;
char tmpstr[4]={0};
DWORD  tmpaddress;
DWORD  tmpaddress1;

if(strstr((const char *)header->section_header[0].Name,".text")!=NULL)
{
virtsize=header->section_header[0].Misc.VirtualSize;
//此段的真实长度
physaddress=header->section_header[0].PointerToRawData;
//此段的物理偏移
physsize=header->section_header[0].SizeOfRawData;
//此段的物理长度
peaddress=dos_head->e_lfanew;
//得到PE文件头的开始偏移

peHeader peH;
tmpaddress=(unsigned long )&peH;
//得到结构的偏移
tmpaddress1=(unsigned long )&(peH.section_header[0].Characteristics);
//得到变量的偏移
flagaddress=tmpaddress1-tmpaddress+2;
//得到属性的相对偏移
flags=0×8000;
//一般情况下,“.text”段是不可读写的,如果我们要把数据写入这个段需要改变其属性,实际上这个程序并没有把数据写入“.text”段,所以并不需要更改,但如果你实现复杂的功能,肯定需要数据,肯定需要更改这个值,

space=physsize-virtsize;
//得到代码段的可用空间,用以判断可不可以写入我们的代码
//用此段的物理长度减去此段的真实长度就可以得到
progRAV=header->opt_head.ImageBase;
//得到程序的装载地址,一般为400000
codeoffset=header->opt_head.BaseOfCode-physaddress;
//得到代码偏移,用代码段起始RVA减去此段的物理偏移
//应为程序的入口计算公式是一个相对的偏移地址,计算公式为:
//代码的写入地址+codeoffset

entrywrite=header->section_header[0].PointerToRawData+header->section_header[0].Misc.VirtualSize;
//代码写入的物理偏移
mods=entrywrite%16;
//对齐边界
if(mods!=0)
{
entrywrite+=(16-mods);
}
oldentryaddress=header->opt_head.AddressOfEntryPoint;
//保存旧的程序入口地址
newentryaddress=entrywrite+codeoffset;
//计算新的程序入口地址        
return;
}

void printaddress()
{
HINSTANCE gLibMsg=NULL;
DWORD funaddress;
gLibMsg=LoadLibrary("user32.dll");
funaddress=(DWORD)GetProcAddress(gLibMsg,"MessageBoxA");
MessageBoxAadaddress=funaddress;
gLibAMsg=LoadLibrary("kernel32.dll");
//得到MessageBox在内存中的地址,以便我们使用
}

void writefile()
{
int ret;
long retf;
DWORD address;
int tmp;
unsigned char waddress[4]={0};

ret=_open(filename,_O_RDWR | _O_CREAT | _O_BINARY,_S_IREAD | _S_IWRITE);
if(!ret)
{
printf("error open\n");
return;
}
    
retf=_lseek(ret,(long)peaddress+40,SEEK_SET);
//程序的入口地址在PE文件头开始的40处
if(retf==-1)
{
printf("error seek\n");
return;
}
address=newentryaddress;
tmp=address>>24;
waddress[3]=tmp;
tmp=address<<8;
tmp=tmp>>24;
waddress[2]=tmp;
tmp=address<<16;
tmp=tmp>>24;
waddress[1]=tmp;
tmp=address<<24;
tmp=tmp>>24;
waddress[0]=tmp;
retf=_write(ret,waddress,4);
//把新的入口地址写入文件
if(retf==-1)
{
printf("error write: %d\n",GetLastError());
return;
}
    
retf=_lseek(ret,(long)entrywrite,SEEK_SET);
if(retf==-1)
{
printf("error seek\n");
return;
}
retf=_write(ret,writeline,18);
if(retf==-1)
{
printf("error write: %d\n",GetLastError());
return;
}
//把writeline写入我们计算出的空间

retf=_lseek(ret,(long)entrywrite+9,SEEK_SET);
//更改MessageBox函数地址,它的二进制代码在writeline[10]处
if(retf==-1)
{
printf("error seek\n");
return;
}

address=MessageBoxAadaddress-(progRAV+newentryaddress+9+4);
//重新计算MessageBox函数的地址,MessageBox函数的原地址减去程序的装载地址加上新的入口地址加9(它的二进制代码相对偏移)加上4(地址长度)
tmp=address>>24;
waddress[3]=tmp;
tmp=address<<8;
tmp=tmp>>24;
waddress[2]=tmp;
tmp=address<<16;
tmp=tmp>>24;
waddress[1]=tmp;
tmp=address<<24;
tmp=tmp>>24;
waddress[0]=tmp;
retf=_write(ret,waddress,4);
//写入重新计算的MessageBox地址
if(retf==-1)
{
printf("error write: %d\n",GetLastError());
return;
}

retf=_lseek(ret,(long)entrywrite+14,SEEK_SET);
//更改返回地址,用jpm返回原程序入口地址,其它的二进制代码在writeline[15]处
if(retf==-1)
{
printf("error seek\n");
return;
}

address=0-(newentryaddress-oldentryaddress+4+15);
//返回地址计算的方法是新的入口地址减去老的入口地址加4(地址长度)加15(二进制代码相对偏移)后取反
tmp=address>>24;
waddress[3]=tmp;
tmp=address<<8;
tmp=tmp>>24;
waddress[2]=tmp;
tmp=address<<16;
tmp=tmp>>24;
waddress[1]=tmp;
tmp=address<<24;
tmp=tmp>>24;
waddress[0]=tmp;
retf=_write(ret,waddress,4);
//写入返回地址
if(retf==-1)
{
printf("error write: %d\n",GetLastError());
return;
}

_close(ret);
printf("\nall done…\n");
return;
}

//end
由于在PE格式的文件中,所有的地址都使用RVA地址,所以一些函数调用和返回地址都要经过计算才可以得到,以上是我在实践中的心得,如果你有更好的办法,真心的希望你能告诉我。

如果存在错误,请告诉我,以免误导看这篇文章的人。
写的较乱,请原谅。

ilsy@netguard.com.cn

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为基础的浏览器,它具有强大的功能,同时为应用开发者留下了广阔的空间,当然它也存在体积比较大,速度相对比较慢的缺点。但是它的体系结构代表了微软先进的创新的技术,因此具有强大的生命力。

0

Toolband (Toolbar for IE) sample using WTL


转至: http://www.codeproject.com

Sample Image - toolband10.gif


Credits and Acknowlegements

This module is based on the ATL DeskBand Wizard article that was created by Erik Thompson. My thanks goes to him for producing a great wizard that saves you the nity grity of creating DeskBands.

Please note that this project does not use MFC, for all those MFC die hards that want to use MFC in their Tool Bands I suggest you down load the KKBar sample from microsofts MSDN site.

The KBBar Sample can be downloaded from here

Creating the ToolBand Module

You will need to install the ATL DeskBand Wizard in order to create ToolBands. Please follow the instruction in this article.

The best way to kick start a Tool band project is to use the ATL COM App Wizard. The COM Object needs to be in-proc therefore choose ‘DLL’ as the Type. The rest of the options can be kept in there default state. (Note this project does not use MFC, as the project is based on ATL and )

Once you have a ATL COM Project, You can use the ATL DeskBand Wizard to create the Initial Tool Band.

Adding Support for WTL

You will require the WTL Libraries, these can be downloaded from the microsoft site

See Installation of WTL

The following header files needs to be added to stdafx.h file

atlapp.hatlwin.hatlctrls.hatlmisc.h

Create the

You can create your toolbar in the usual way via the resource editor, Once you have your toolbar you need to create the toolbar dynamically. The CBandToolBarCtrl is inherited from CToolBarCtrl and is used to create the toolbar dynamically.

DWORD dStyle = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS |                CCS_NODIVIDER | CCS_NORESIZE | CCS_NOPARENTALIGN |                TBSTYLE_TOOLTIPS | TBSTYLE_FLAT;    HWND hWnd = m_wndToolBar.CreateSimpleToolBarCtrl(hWndChild, IDR_TOOLBAR_TEST,                                                  FALSE, dStyle); 

This is done in the RegisterAndCreateWindow function that is called from SetSite method.

Message Reflection

The best way to handle the messages of the toolbar is to let the control handle its own messages via "Message Reflection". The best way to reflect the messages is to create an invisible control that acts as the parent for the toolbar. The invisible control will reflect the toolbar messages back to itself. See CBandToolBarReflectorCtrl for the invisible control that will be used.

The following code shows the parent child relationship that is used to achieve Message Reflection.

BOOL CToolBandObj::RegisterAndCreateWindow(){    RECT rectClientParent;    ::GetClientRect(m_hWndParent, &rectClientParent);    // We need to create an Invisible Child Window using the Parent Window,     // this will also be used to reflect Command    // messages from the rebar    HWND hWndChild = m_wndInvisibleChildWnd.Create(m_hWndParent,                                                    rectClientParent,                                                    NULL, WS_CHILD);        // Now we can create the Tool Bar, using the Invisible Child    DWORD dStyle = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS |                    CCS_NODIVIDER | CCS_NORESIZE | CCS_NOPARENTALIGN |                    TBSTYLE_TOOLTIPS | TBSTYLE_FLAT;        HWND hWnd = m_wndToolBar.CreateSimpleToolBarCtrl(hWndChild,

                                                     IDR_TOOLBAR_TEST,                                                      FALSE, dStyle);     m_wndToolBar.SetExtendedStyle(TBSTYLE_EX_DRAWDDARROWS);              m_wndToolBar.m_ctlBandEdit.m_pBand = this;    return ::IsWindow(m_wndToolBar.m_hWnd);}

The following Macros are used to identify the reflected messages from the ordinary messages. e.g WM_COMMAND reflected comes back as OCM_COMMAND.

#define OCM_COMMAND_CODE_HANDLER(code, func) \if(uMsg == OCM_COMMAND && code == HIWORD(wParam)) \{ \    bHandled = TRUE; \    lResult = func(HIWORD(wParam), LOWORD(wParam), (HWND)lParam, bHandled); \    if(bHandled) \    return TRUE; \}#define OCM_COMMAND_ID_HANDLER(id, func) \if(uMsg == OCM_COMMAND && id == LOWORD(wParam)) \{ \    bHandled = TRUE; \    lResult = func(HIWORD(wParam), LOWORD(wParam), (HWND)lParam, bHandled); \    if(bHandled) \    return TRUE; \}#define OCM_NOTIFY_CODE_HANDLER(cd, func) \if(uMsg == OCM_NOTIFY && cd == ((LPNMHDR)lParam)->code) \{ \    bHandled = TRUE; \    lResult = func((int)wParam, (LPNMHDR)lParam, bHandled); \    if(bHandled) \    return TRUE; \}

Browser Navigation

In order to Navigate on the browser you need to instantiate the IWebBrowser2 COM Object. This is usually done on the SetSite Method e.g.

IServiceProviderPtr pServiceProvider = pUnkSite;if (_Module.m_pWebBrowser)    _Module.m_pWebBrowser = NULL; if(FAILED(pServiceProvider->QueryService(SID_SWebBrowserApp, IID_IWebBrowser,                                             (void**)&_Module.m_pWebBrowser)))return E_FAIL;

Once you have the COM Object Instantiated, you can move to your URL using the navigate method

	_variant_t varURL = _bstr_t(www.codeproject.com); _variant_t varEmpty;_Module.m_pWebBrowser->Navigate2(&varURL, &varEmpty, &varEmpty,                                     &varEmpty, &varEmpty);

Drag and Drop Edit and ComboBox Control

The CBandEditCtrl class is inherited from a WTL CEdit control that has drag and drop facility. i.e. you can drag text from the browser straight to the CEdit Control.

The CBandComboBoxCtrl class is inherited from a WTL CComboBox control that has drag and drop facility. i.e. you can drag text from the browser straight to the CComboBox Control.

Drag and Drop URL - toolband2.gif

The Edit control in this sample module allows you to drag a URL from Explorer or any other Dragable enabled container. Once you have dropped the URL the toolband will go to that site.

Configurable Toolbar Button Styles

The CBandToolBarCtrl class allows you to have the follwoing button styles on the toolbar

  • Image and Text on the right
  • Image and Text on the bottom
  • Image only

Text on Right - toolband3.gif

No Text - toolband4.gif

Text Under - toolband5.gif

Pop-up Menu Tracking

A pop up menu is used to get to the configuration options

Popup Menu Tracking - toolband6.gif

ToolTips

This has been taken from MSDN to explain why you need to handle the tooltips on the toolbar your self.

Tool tips are automatically displayed for buttons and other controls contained in a parent window derived from CFrameWnd. This is because CFrameWnd has a default handler for the TTN_GETDISPINFO notification, which handles TTN_NEEDTEXT notifications from tool tip controls associated with controls.

However, this default handler is not called when the TTN_NEEDTEXT notification is sent from a tool tip control associated with a control in a window that is not a CFrameWnd, such as a control on a dialog box or a form view. Therefore, it is necessary for you to provide a handler function for the TTN_NEEDTEXT notification message in order to display tool tips for child controls.

This can be easily done in WTL by using the following Message Handler in the overriden ToolBar Control

NOTIFY_CODE_HANDLER(TTN_NEEDTEXT, OnToolbarNeedText)

The following is the code that loads the tool tips from the resources and sets the tool tip text.

LRESULT CBandToolBarCtrl::OnToolbarNeedText(int /*idCtrl*/, LPNMHDR pnmh, BOOL&                                             bHandled)	{    CString sToolTip;        //-- make sure this 1is not a seperator    if (idCtrl != 0)     {        if (!sToolTip.LoadString(idCtrl))        {            bHandled = FALSE;            return 0;        }    }    LPNMTTDISPINFO pttdi = reinterpret_cast<LPNMTTDISPINFO>	    (pnmh);pttdi->lpszText = MAKEINTRESOURCE(idCtrl);    pttdi->hinst = _Module.GetResourceInstance();    pttdi->uFlags = TTF_DI_SETITEM;    //-- message processed    return 0;}

Update the Status Bar

You can update the status bar using the browser method put_StatusText, this method can be used typically in the WM_MENUSELECT event

The following is the code that loads up the menu text from the resources and displays it on the browser status bar.

Collapse
LRESULT CBandToolBarCtrl::OnMenuSelect(UINT /*uMsg*/,                                        WPARAM wParam, LPARAM lParam,                                        BOOL& bHandled) {    WORD nID = LOWORD(wParam);    WORD wFlags = HIWORD(wParam);        //-- make sure this is not a seperator    CString sStatusBarDesc;    if ( !(wFlags & MF_POPUP) )    {        if (nID != 0)         {            if (!sStatusBarDesc.LoadString(nID))            {	        bHandled = FALSE;                return 0;            }            int nPos = sStatusBarDesc.Find(_T("\n"));            if (nPos != -1)            {                sStatusBarDesc =                 sStatusBarDesc.Left(nPos+1);                _Module.m_pWebBrowser->                put_StatusText(_bstr_t(sStatusBarDesc));                return 0;            }        }    }    return 0;}

How to add a Chevron to your toolband

In order to add a chevron to your toolband you need to add the DBIMF_USECHEVRON flags to your GetBandInfo method in the DBIM_MODEFLAGS mask.

 ... if(pdbi->dwMask == DBIM_MODEFLAGS)     {         //AddChevron        pdbi->dwModeFlags = DBIMF_NORMAL | DBIMF_VARIABLEHEIGHT |                                   DBIMF_USECHEVRON | DBIMF_BREAK;    }...

This basically add the ability to show the chevron, if you want to see it appear on your toolband, then you must make sure the pdbi->ptMinSize.x value is less then your pdbi->ptActual.x value (Again this values can be set in the GetBandInfo method.

In order to handle the events of the button in the chevron menu, you must subclass the rebar control which is hosting your toolbar. The following steps have been used to sublass the rebar control

1. Find the rebar control – This can be achieved by getting the browsers window handle and searching for all its child , until you find the rebar control.

2. Once you have found the rebar control you can simply subclass it using an ATL CContainedWindow.

    BOOL CBandToolBarCtrl::SetBandRebar()    {         HWND hWnd(NULL);        _Module.m_pWebBrowser->get_HWND((long*)&hWnd);         if (hWnd == NULL) 	    return FALSE;	m_ctlRebar.m_hWnd = FindRebar(hWnd);	if (m_ctlRebar.m_hWnd == NULL) 	    return FALSE;	m_RebarContainer.SubclassWindow(m_ctlRebar);	return TRUE;    }

Once you have subclass the window, the events should reach the toolbar class.

Append to the Browser Context Menu

Sample Image - toolband11.gif

I tried to duplicate the google and codeproject toolband right mouse browser context menu searches without any luck, until I looked at the binary resources, I found that you can extend the internet explorer menu by adding the option in the registry. This can easily be achieved by adding an entry in your .rgs file.

HKCU{    NoRemove Software    {        NoRemove Microsoft        {            NoRemove 'Internet Explorer'            {                NoRemove MenuExt                {                    ForceRemove '&Sample Toolband Serach' = s'res://%MODULE%/MENUSEARCH.HTM'                    {                        val Contexts = b '10'                    }                }            }        }    }}

Note the value of the registry item (a script that exist in the resources of the module).

see MENUSERACH.HTM under HTML in the module resource to see what the script is doing

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 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 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 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\ 下给出 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

(转)lucene安装


网上有许多lucene的材料,中文材料大家看的都是车东的那篇(http://www.chedong.com/tech/.),而大家在网上讨论最多的是中文的全文检索,而对中文的全文检索最有影响力的文章,还是车东写的那篇weblucene(http://www.chedong.com/tech/weblucene.),但那些都是lucene1.2版本的事,现在不同了,1.3-final据称完全支持中文的全文检索了。
因为在lucene1.3-final.zip包中的changes.txt中的第五项描述如下:
5. Fix StandardTokenizer’s handling of CJK characters (Chinese,
 Japanese and Korean ideograms). Previously contiguous sequences
 were combined in a single token, which is not very useful. Now
 each ideogram generates a separate token, which is more useful.
这说明lucene1.3-final可以检索中日韩等表意文字了。

测试一下:
测试环境: 2000 pro,jdk1.3.1或以上版本
1、下载lucene-1.3-final.zip。

2、解压lucene-1.3-final.zip,并将其中的lucene-1.3-final.jar和lucene-demos-1.3-final.jar加入到系统的classpath中。

3、建一个目录,并将一些html或txt文件(文件内容要中文的!)拷入到这个目录中,作为全文检索的材料。如:建一个目录d:\lucenetest\index,在其中拷入一些中文内容的文件,其中也可以有多级子目录的。
OK,环境准备好了,可以试验了!

4、进入dos模式,输入命令: org.apache.lucene.demo.IndexFiles d:\lucenetest\index
如:c:\>java org.apache.lucene.demo.IndexFiles d:\lucenetest\index 回车,这时会索引d:\lucenetest\index目录下的所有文件,包括子目录中的文件,并将索引文件写入:c:\index目录中(自动创建的,根据你的dos符起始路径,将在其下建index目录)。
好,索引建完了,下面试验检索。

5、输入命令:java org.apache.lucene.demo.SearchFiles
如:c:\>java org.apache.lucene.demo.SearchFiles 回车
Query:在这里输入检索内容,如:“建议最好自己先做一下语法检查”,这么长:)
成功了,结果出来了:
Searching for: “建 议 最 好 自 己 先 做 一 下 语 法 检 查”
1 total matching documents
0. d:\lucenetest\index\学习Lucene的一点心得.txt
可以看出lucene-1.3-final完全支持中文的全文检索了,使用的是单字切分!!

0

目前主流开发技术的分析和总结


转至: www.csdn.net

主流的程序设计语言:C++、Delphi(ObjectPascal)、、C#

  桌面应用程序框架:MFC、VCL、QT、JavaAWT\SWING、.Net

  企业应用程序框架:WindowsDNA(ASP、COM、COM+)、J2EE、.NetFramework

  开发工具:VisualBasic、Delphi、VisualC++、C++Builder、VisualC#
*程序设计语言:C++\Delphi(本来应该是ObjectPascal,但为了简单,我就语言和工具混为一谈吧)\Java\C#(虽然他刚刚推出,但因为微软为之倾注了大量心血,一定会成为一种重要的开发语言)

   *桌面应用程序框架:MFC\VCL

   *企业应用程序框架:WindowsDNA\J2EE\.Net

   *COM技术:我单独提出这项技术,是因为它无法简单的被视为语言、桌面应用程序框架或企业应用程序框架,它与这些都有关系。

  2.1 程序设计语言

  2.1.1 C++语言的演进

   最初要从二进制代码和汇编说起,但那太遥远了。我们就从面向过程的语言说起吧(包括Basic\C\Fortran\Pascal)。这种面向过程的高 级语言终于把计算机带入了寻常的应用领域。其中的C语言因为它的简单和灵活造就了Unix和Windows这样的伟大的软件。

  面向对象 的语言是计算机语言的一个合乎逻辑的进化,因为在没有过多的影响效率、简单性的前提下提供了一种更好的组织数据的方法,可使程序更容易理解,更容易管理 ——这一点可能会引出不同意见,但事实胜于雄辩,C++终于让C语言的领地越来越小,当今还活着的计算机语言或多或少的都具备面向对象的特征,所以这一点 并不会引起太多困惑。C++的成功很大程度要归因于C,C++成为它今天的样子是合乎逻辑的产物。因为在面向过程的时代,C几乎已经统一天下了。今天著名 的语言象Java\C#都从C借鉴了很多东西,C#本来的意思就是C++++。其实C++曾经很有理由统一面向对象程序设计语言的天下来着,但可惜的是, C++太复杂了。即使是一个熟练的程序员,要你很清楚的解释一些问题你也会很头痛。举几个还不是那么复杂的例子来说:

  对=的重载\成员转换函数\拷贝构造函数\转化构造函数之间有什么区别和联系呢?

  定义一个类成员函数private:virtualvoidMemFun()=0;是什么意义呢?

  int(*(*x(int))[4])(double);是什么意思?

   还有其他的特征,比如说可以用来制造一种新语言的typedef和宏(虽然宏不是C++的一部分,但它与C++的关系实在太密切了),让你一不小心就摔 跤的内存问题(只要new和delete就可以了吗?有没有考虑一个对象存放在容器中的情况?)……诸如此类,C++是如此的复杂以至于要学会它就需要很 长的时间,而且你会发现即使你用C++已经好几年了,你还会发现经常有新东西可学。你想解决一个应用领域的问题——比如说从数据库里面查询数据、更改数据 那样的问题,可是你却需要首先为C++头痛一阵子才可以,是的,你精通C++,你可以很容易的回答我的问题,可是你有没有想过你付出了多大的代价呢?我不 是想过分的谴责C++,我本人喜欢C++,我甚至建议一个认真的开发普通的应用系统的程序员也去学习一下C++,C++中的一些特性,比如说指针运算\模 板\STL几乎让人爱不释手,宏可以用几个字符代替很多代码,对系统级的程序员来说,C++的地位是不可替代的,Java的虚拟机就是C++写的。C++ 还将继续存在而且有旺盛的生命力。
2.1.2 Java和C#

  Java和C#相对于C++的不同最大的有两点:第一点是他们运 行在一个虚拟环境之中,第二点是语法简单。对于开发人员而言,在语法和语言机制的角度可以把Java和C#视为同一种语言。C#更多的是个政治的产物而不 是技术产物。如果不是Sun为难微软的话,我想微软不会费尽心力推出一个和Java差不多的C++++,记得Visual J++吗,记得WFC吗?看看那些东西就会知道微软为Java曾经倾注了多少心血。而且从更广泛的角度来说,两者也是非常相似的——C#和Java面对的 是同样的问题,面向应用领域的问题:事务处理、远程访问、Webservice、Web页面发布、图形界面。那么在这一段中,我暂且用Java这个名字指 代Java和C#两种语言——尽管两者在细节上确实有区别。Java是适合解决应用领域的问题的语言。最大的原因Java对于使用者来说非常简单。想想你 学会并且能够使用Java需要多长时间,学会并且能够使用C++要多长时间。由于Java很大程度上屏蔽了内存管理问题,而且没有那么多为了微小的性能提 升定义的特殊的内容(比如说,在Java里面没有virtual这个关键字,Java也不允许你直接在栈上创建对象,Java明确的区分bool和整型变 量),他让你尽量一致的方式操作所有的东西,除了基本数据类型,所有的东西都是对象,你必须通过引用来操作他们;除了这些之外,Java还提供了丰富的类 库帮助你解决应用问题——因为它是面向应用的语言,它为你提供了多线程标准、JDBC标准、GUI标准,而这些标准在C++中是不存在的,因为C++并不 是直接面向解决应用问题的用户,有人试图在C++中加入这些内容,但并不成功,因为C++本身太复杂了,用这种复杂的语言来实现这种复杂的应用程序框架本 身就是一件艰难的事情,稍后我们会提到这种尝试——COM技术。渐渐的,人们不会再用C++开发应用领域的软件,象MFC\QT\COM这一类的东西最终 也将退出历史舞台。

  2.1.3 Delphi

  Delphi是从用C++开发应用系统转向用Java开发应用系统的一 个中间产物。它比C++简单,简单的几乎象Java一样,因为它的简单,定义和使用丰富的类库成为可能,而且Delphi也这么做了,结果就是VCL和其 他的组件库。而另一方面,它又比运行于虚拟环境的Java效率要高一些,这样在简单性和效率的平衡之中,Delphi找到了自己的生存空间。而且预计在未 来的一段时间之内,这个生存空间将仍然是存在的。可以明显的看出,微软放弃了这个领域,他专注于两方面:系统语言C++和未来的Java(其实是. Net)。也许这对于Borland来说,是一件很幸运的事情。如果我能够给Borland提一些建议的话,那就是不要把Delphi弄得越来越复杂,如 果那样,就是把自己的用户赶到了C++或Java的领地。在虚拟机没有最终占领所有的应用程序开发领域之前,Delphi和Delphi的用户仍然会生存 得很好。

  2.2桌面应用程序框架

  目前真正成功的桌面应用程序框架只有两个,一个是MFC,一个是VCL,还有一些其他的,但事实上并未进入应用领域。遗憾的是我对两个桌面应用程序框架都不精通。但这不妨碍我对他做出正确的评价。

  2.2.1MFC

   MFC(还有曾经的OWL)是SDK编程的正常演化的结果,就象是C++是C的演化结果一样。MFC本身是一件了不起但不那么成功的作品,而且它过时 了。这就是我的结论。MFC凝聚了很多天才的智慧——当然,OWL和VCL也一样,侯捷的《深入浅出MFC》把这些智慧摆在了我们的面前。但是这件东西用 起来估计不会有人觉得很舒服,如果你一直在用Java、VB或者Delphi,再回过头来用MFC,不舒服的感觉会更加强烈。我不能够解释MFC为什么没 有能够最终发展成和VCL一样简单好用的桌面程序框架,也许是微软没精力或者没动力,总之MFC就是那个样子了,而且也不会再有发展,它已经被抛弃了。我 有时候想,也许基于C++这种复杂的语言开发MFC这样的东西本身就是错误的——可以开发这样的一个框架,但不应当要求使用它的人熟悉了整个框架之后才能 够使用这个系统,但很显然,如果你不了解MFC的内部机制,是不太可能把它用好的,我不能解释清楚为什么会出现这种现象。

  2.2.2VCL

   相比之下VCL要成功的得多。我相信很多使用VCL的人可能没有像MFC的用户研究MFC那样费劲的研究过VCL的内部机制。但这不妨碍他们开发出好用 好看的应用程序,这就足够了,还有什么好说的呢?VCL给你提供了一种简单一致的机制,让你可以写出复杂的应用程序。在李维的Borland故事那篇文章 中曾经说过,在Borland C++ 3.1推出之后Borland就有人提出开发类似C++ Builder一类的软件,后来竟未成行。是啊,如果C++ Builder是在那个时候出现的,今天的软件开发领域将会是怎么样的世界呢?真的不能想象。也许再过一段时间,这些都将不再重要。因为新生的语言如 Java和C#都提供了类似于VCL的桌面应用程序框架。那个时候,加上Java和C#本身的简单性,如果他们的速度有足够块,连Delphi这种语言也 要消失了,还有什么好争论的呢?只是对于今天的桌面程序开发人员来说,VCL确实是最好的选择。
2.3 企业应用程序框架

  2.3.1 DNA

   Windows DNA的起源无从探究了。随着.Net的推出,事实上Windows DNA将成为历史的陈迹。Windows DNA虽然是几乎所有的企业应用程序开发人员都知道的一个名词,但我相信Windows DNA事实上应用的最广泛的是ASP而不是COM+。真正的COM开发有多少人真正的掌握了呢,更不要提COM+(我有必要解释一下:COM+是COM的 执行环境,它提供了一系列如事务处理、安全等基础服务,让应用程序开发人员尽量少在基础架构设计上花精力)——当然我这里指的COM开发不是指VB下的 COM开发,所以要这么说,是因为我觉得如果不能理解用C++进行COM开发,也就不能真正的理解COM技术。如果以一种技术没有被广泛理解和应用作为失 败的标志,那么Windows DNA实际上是失败了,但这不是它本身的错,而是基于C++的COM技术的失败造成的。多层应用、系统开发角色分离的概念依然没有过时。
 2.3.2 J2EE

   J2EE是第一套成功的企业应用程序开发框架。因为它把事务处理、远程访问、安全这些概念带入了寻常百姓家。这种成功我认为要归因于Java的简单性。 Java的简单,对于J2EE容器供应商来说一样重要。开发一个基于Java的应用服务器要比基于C++的更容易。而且由于Java的简单性,应用系统开 发者出错的机会也会少一些,不会像C++的开发者那样受到那么多挫折。开发基于Java的企业应用系统的周期会更短,这恐怕是不容争辩的事实。不论如何, 是J2EE让事务处理、远程访问、安全这些原来几乎都是用在金融系统中的概念也被一般的企业用户使用并从中获得利益。

  2.3.3 .NET

   .Net有什么好说的呢?其实,它不过是微软的J2EE。事务处理、安全、远程访问,这些概念在.Net中都找得到。更有力的说明是,微软也利用了. Net实现了一个PetStore。所以,.Net与J2EE几乎是可以完全对等的。但微软确实是一家值得尊敬的公司——我指从技术上,象Web form这种东西,我相信很多Web应用开发者都梦想过甚至自己实现过,但Sun却一直无动于衷,而且似乎Borland也没有为此作过太多努力,好像有 过类似的东西,但肯定是不怎么成功——Borland已经很让人敬佩了,我们也许无法要求太多。
2.4 COM技术

  COM应当 是个更广泛的词汇,其实我觉得Axtive X、OLE、Auto mation、COM+都应当提及,因为如果你不理解COM,上面的东西你是无法理解的。而且,我只是想说明COM是一种即将消亡的技术,仅仅说说COM 的复杂性和他的问题就够了,所以不会提及那些东西。为什么会出现COM技术?COM的根本目标是实现代码的对象化的二进制重用,进而实现软件的组件化、软 件开发工作的分工。这要求他做到两点:第一,能够跨越不同的语言,第二,要跨越同一种语言的不同编译器。COM技术为这个目标付出了沉重的代价,尤其是为 了跨越不同的编译器,以至于无论对于使用者而言还是开发者而言,他都是一个痛苦的技术。但幸运的事,这一切终归要结束了。

  让我们从这个 目的出发看看COM为什么会成为它现在的样子。其实COM不是什么新玩意,最初的DLL就是重用二进制代码的技术。DLL在C的年代可能还不错,但到了C ++的年代就不行了。原因在于如果你在.h文件中改变了类定义(增加或者减少了成员变量),代码库用户的代码必须重新编译才可以,否则用户的代码会按你的 旧类的结构为你的新类分配内存,这将产生什么后果可想而知。这就是为什么通过接口继承和通过接口操作对象成为COM的强制规范的原因,能够通过对象的方式 组织代码是COM的重要努力。那么著名的IUnknown接口又是怎么回事呢?这是为了让使用不同编译器的C++开发人员能够共享劳动成果。

 

   首先看QueryInterface,因为COM是基于接口的,那么一个类可能实现了几个接口,而对于用户来说,你又只能通过操作接口来操作类,这样你 必须把类造型成某个特定的接口,使用Dynamic_cast吗?不行,因为这是编译器相关的,那么,就只好把它放在类的实现代码中了,这就是 QueryInterface的由来。至于AddRef和Release,他们产生的第一个原因是delete这个操作要求一个类具有虚析构函数(否则的 话,他的父类的析构函数将不会被调用),但不幸的是不同的编译器中析构函数在vtbl中的位置并不相同,这就是说你不能让用户直接调用delete,那么 你的COM对象必须提供自己删除自己的方法;另外的原因在于一个COM对象可能作为几个接口在被用户同时使用,如果用户粗暴的删掉了某个接口,那么其他的 接口也就不能用了,这样,只好要求用户在想用一个接口的时候通过AddRef通知COM对象“我要使用你了,你多了一个用户”,而在不用之后要调用 Release告诉COM对象“我不用你了,你少了一个用户”,如果COM对象发现自己没有用户了,它就把自己删掉。

  再看看诡异的 HRESULT,这是跨语言和跨编译器的代价。其实,异常处理是物竞天择的结果——连一直用效率作标榜的C++都肯牺牲效率来实现这个try- catch,可见它的意义,但COM为了照顾那些低级的语言居然抛弃了这个特征——产生的结果就是HRESULT。我们可以看看他是多么愚蠢的东西。首 先,我们要通过一个整数来传递错误信息,通过IErrorInfo来查找真正的错误描述,本来在现代语言中一个try-catch可以解决的问题,现在我 们却需要让用户和开发者都走很多路才能解决,你怎么评价这个结果?其次,由于这个返回计算结果的位置被占用了,我们不得不用怪异的out参数来返回结果。 想想一个简单的int add(intop1,intop2)在COM中竟然要变成HRESULT add(intop1,intop2,int* result),我不知道你对此作何感想。而且由于COM的方法无法返回一个对象而只能返回一个指针,为了完成一个简单的std::string GetName()这一类的操作,你要费多少周折——你需要先分配一块内存空间,然后在COM实现中把一个字符串拷贝到这个空间,用完了你要删掉这个空 间,不知道你是否觉得这种工作很幸福,反正我觉得很痛苦。还有COM为了照顾那些解释性的语言,又加入了Automation技术,你有没有为此觉得痛 苦?本来一个简单的方法调用,现在却需要传给你一个标志变量,然后让你根据这个标志变量去执行相应的操作。(这一点我现在仍然不明白,为什么解释性的语言 需要通过这个方式来执行一个方法)。“我受够了,我觉得头痛”,你会说,是啊,我想所有的人都受够了,所有这些因素实际上是把COM技术变成了一头让人无 法驾驭的怪兽。

  人对复杂事物的掌控能力终究是有限的,C++本身已经够复杂了,COM的复杂性已经超出了我们大部分人的控制能力,你需 要忍受种种痛苦得到的东西与你付出的代价相比是不是太不值得了?我们学习是为了解决问题,而现在我们却需要为了学习这件事情本身耗费太多的精力。这些痛苦 的东西太多了,我在这里说到的,其实只是一小部分而已。计算机技术是为人类服务的,而不是少数人的游戏(我想COM技术可能是他的设计者和一部分技术作者 的游戏),难道我们愿意成为计算机的奴隶吗?通过一种过于复杂的技术抛弃所有的人其实等于被所有的人抛弃,这么多年中选择J2EE的人我相信不乏高手,你 是不是因为COM的过于复杂才选择J2EE的?因为它可以用简单的途径实现差不多的目标——软件的“二进制”重用、组件化、专业分工(容器开发商和应用开 发商的分工)。事实上,你是被微软所抛弃的,同时,你也抛弃了微软。

  现在让我们回来吧,我把你带进了COM的迷宫,现在让我把你领回 来。再让我们看看COM到底想实现什么目标,其实很简单,不过是代码的二进制重用,也就是说你不必给别人源代码,而且你的组件可以象计算机硬件那样“即插 即用”。我们回过头来看看Java,其实,这种二进制重用的困难是C++所带来的(这不是C++本身的错,而是静态编译的错),当Java出现的时候,很 多问题已经不存在了。你不需要一个头文件,因为Java的字节码是自解释的,它说明了自己是什么样子的,可以做什么事情。不像C++那样需要一个头文件来 解释这些事情;也不需要事先了解对象的内存结构,因为内存是在运行的时候才分配的。如果我们现在再回过头来解决COM要解决的问题,你会怎么做呢?首先你 会不再选择C++这种语言来实现代码的“二进制”重用,其次,你会把所有的语言编译成同样的“二进制”代码(实际上,应当说是字节码),这显然是更聪明的 做法,从前COM试图在源代码的级别抹平二进制层次的差异,这实际上是让人在做本来应当由机器做的事情,很愚蠢是吗?但他们一直做了那么多年,而且把这个 痛苦带给了整个计算机世界——因为他们掌握着事实的标准,为了用户,为了利润,为了能够在Windows上运行,尽管你知道你在做着一个很不聪明的事情, 但你还是做了。

  COM技术为了照顾VB这个小兄弟和实现统一二进制世界的野心,实在浪费了太多的精力。首先,落后的东西的消亡是必然 的,就象C、Pascal在应用领域的消亡一样,Basic一点一点的改良运动是不符合历史潮流的做法,先进的东西和落后的东西在一起,要么先进的东西被 落后的东西拖住后腿,要么是同化落后的东西,显然我们更愿意看见后者,现在Basic终于被现代的计算机语言同化了。其次,统一二进制世界好像不是那么简 单的事情,而且也没什么必要,微软的COM技术奋战了10年,现在也只有他自己和Borland支持,.Net终于放弃了这个野心。这一切终于要结束了。

过去J2EE高歌猛进地占领着应用开发的领地,COM在这种进攻面前多少显得苍白无力。现在微软终于也有了可以和J2EE一较长短的.NET,对于开发 人员来讲,基于字节码的组件的二进制重用现在是天经地义的事情;你不用再为了能够以类方式发布组件做那么多乱七八糟的事情,因为现在所有的东西本来就是类 了;实现软件开发的分工也很自然,你是专业人员,就用C#吧,你是应用开发人员,你喜欢用VB.Net,你就用吧,反正你们写的东西最终都被翻译成了一样 的语言(其实我觉得这一点意义不大,因为一些不那么好用的语言被淘汰是正常的事情,C风格成为程序设计语言的主流风格,肯定是有它的原因的,语言的统一其 实是大势所趋,就象中国人民都要说普通话一样,我觉得Java不支持多语言算不上缺点——本来就是一种很好看很好用的语言了,为什么要把简单问题复杂化 呢?)。COM不会在短期内死去,因为我估计微软还不会马上用C#开发Office和Windows的图形界面部分,但我相信COM技术退出历史舞台的日 子已经不远了,作为一般的开发人员,忘了这段不愉快的历史吧——你将不会在你的世界里直接和COM打交道。若干年以后,我想COM也许会成为一场笑话,用 来讽刺那种野心过大、钻牛角尖的愚蠢的聪明人。

0

如何屏蔽控制台应用程序的窗口?


Step1. Create a console application.

Step2. Add following segment before main() entry function:
            #pragma comment( linker, "/subsystem:\"\" /entry:\"mainCRTStartup\"" )

Step3. Try to build it.

Previous Page Next Page

Random Posts Recent Comments

  • Nouramohsen88 Says:

    http://goo.gl/vFWge لدينا ثلاجات عرض جديدة ومستعملة للبيع ولدينا ثلاجات عرض سوبر ماركت وحلويات في ست...

  • Nouramohsen88 Says:

    http://www.drdrahem.com/home دكتور رجيم دكتور تخسيس الكرش والارداف مركز تخسيس في مدينة نصر ...

  • Nouramohsen88 Says:

    شركه تصنيع صاعق ناموس http://www.grandelectronic-eg.com/...

  • Nouramohsen88 Says:

    شركة كشافات اضاءة في مصر http://www.grandelectronic-eg.com/ ...

  • Nouramohsen88 Says:

    http://www.grandelectronic-eg.com/ شركة كشافات طواريء في مصر...

  • Nouramohsen88 Says:

    anti-mosquitocompany.blogspot.com شركة جراند الكترونيك هي شركة مصرية متخصصة في تصنيع الكشافات الكهرب...

  • Nouramohsen88 Says:

    insect--killer.blogspot.com شركة جراند الكترونيك هي شركة مصرية متخصصة في تصنيع الكشافات الكهربية وك...

  • Nouramohsen88 Says:

    http://genius-square.com/ شركه للتدريب والاستشارات | متخصصون في التنمية البشرية...

  • Er Says:

    我了个去,我也是用的phpo ..... 看来大家的思绪差不多。。。。...

  • Fasf Says:

    SYM_TYPE * pType;改为SYM_TYPE pType;...

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 优化 动态加载 女人 女生 平台 开发 手机 技术 流媒体 测试 漫画 生活 男人 男生 缓存 芯片