1.250定律
拉德认为:每一位顾客身后,大体有250名亲朋好友。如果您赢得了一位顾客的好感,就意味着赢得了250个人的好感;反之,如果你得罪了一名顾客,也就意味着得罪了250 名顾客。 在你的网站访客中,一个访客可能可以带来一群访客,任何网站都有起步和发展的过程,这个过程中此定律尤其重要。
2.达维多定律
达维多认为,一个企业要想在市场上总是占据主导地位,那么就要做到第一个开发出新产品,又第一个淘汰自己的老产品。 国内网站跟风太严重,比如前段时间的格子网,乞讨网,博客网,一个成功了,大家一拥而上。但实际效果是,第一个出名的往往最成功,所以在网站的定位上,要动自己的脑筋,不是去捡人家剩下的客户。同理,买人家出售的数据来建站效果是很糟糕的。
3.木桶定律
水桶定律是指,一只水桶能装多少水,完全取决于它最短的那块木板。这就是说任何一个组织都可能面临的一个共同问题,即构成组织的各个部分往往决定了整个组织的水平。 注意审视自己的网站,是速度最糟糕?美工最糟糕?宣传最糟糕?你首先要做的,不是改进你最强的,而应该是你最薄弱的。
4.马太效应
《新约》中有这样一个故事,一个国王远行前,交给三个仆人每人一锭银子,吩咐他们:“你们去做生意,等我回来时,再来见我。”国王回来时,第一个仆人说: “主人,你交给我们的一锭银子,我已赚了10锭。”于是国王奖励他10座城邑。第二个仆人报告说:“主人,你给我的一锭银子,我已赚了5锭。” 于是国王例奖励了他5座城邑。第三个仆人报告说:“主人,你给我的一锭银子,我一直包在手巾里存着,我怕丢失,一直没有拿出来。”于是国王命令将第三个仆人的一锭银子也赏给第一个仆人,并且说:“凡是少的,就连他所有的也要夺过来。凡是多的,还要给他,叫他多多益善。”这就是马太效应。 在同类网站中,马太效应是很明显的。一个出名的社区,比一个新建的社区,更容易吸引到新客户。启示是,如果你无法把网站做大,那么你要做专。作专之后再做大就更容易。
5.手表定理
手表定理是指一个人有一只表时,可以知道现在是几点钟,而当他同时拥有两只表时却无法确定。
一个网站,你只需要关注你特定的用户群需求。不要在意不相干人的看法。
6.不值得定律
不值得定律:不值得做的事情,就不值得做好 不要过度seo,如果你不是想只做垃圾站。不要把时间浪费在美化再美化页面,优化再优化程序,在你网站能盈利后,这些事情可以交给技术人员完成。
7.彼得原理
劳伦斯.彼得认为:在各种组织中,由于习惯于对在某个等级上称职的人员进行晋升提拔,因而雇员总是趋向于晋升到其不称职的地位。
不要轻易改变自己网站的定位。如博客网想变门户,盛大想做娱乐,大家拭目以待吧。
8.零和游戏原理
当你看到两位对弈者时,你就可以说他们正在玩“零和游戏”。因为在大多数情况下, 总会有一个赢,一个输,如果我们把获胜计算为得1分,而输棋为-1分,那么,这两人得分之和就是:1+(-1)=0 不要把目光一直盯在你的竞争网站上,不要花太多时间抢它的访客。我们把这些时间用来寻找互补的合作网站,挖掘新访客。
9.华盛顿合作规律
华盛顿合作规律说的是: 一个人敷衍了事,两个人互相推诿, 三个人则永无成事之日。
如果你看准一个方向,你自己干,缺人手就招。不要轻易找同伴一起搞网站,否则你会发现,日子似乎越过越快了,事情越做越慢了。
10.邦尼人力定律
一个人一分钟可以挖一个洞,六十个人一秒种却挖不了一个洞。合作是一个问题,如何合作也是一个问题。你需要有计划。
11.牛蛙效应
把一只牛蛙放在开水锅里,牛蛙会很快跳出来;但当你把它放在冷水里,它不会跳出来,然后慢慢加热,起初牛蛙出于懒惰,不会有什么动作,当水温高到它无法忍受的时候,想出来,但已经没有了力气。 如果你是soho,注意关注你的财务。不要等到没钱了再想怎么挣,你会发现那时候挣钱更难。
12.蘑菇管理
蘑菇管理是许多组织对待初出茅庐者的一种管理方法,初学者被置于阴暗的角落(不受重视的部门,或打杂跑腿的工作),浇上一头大粪(无端的批评、指责、代人受过),任其自生自灭(得不到必要的指导和提携)。
做网站毕竟要遭遇这样的阶段,搜索引擎不理你,友情链接找不到,访客不上门。这是磨练。
13.奥卡姆剃刀定律
如无必要,勿增实体。
把网站做得简单,再简单,简单到非常实用,而不是花俏。google的首页为什么比雅虎好?
14.巴莱多定律(Paredo 也叫二八定律)
你所完成的工作里80%的成果,来自于你20%的付出;而80%的付出,只换来20%的成果。
随时衡量你所做的工作,哪些是最有效果的。
1.马蝇效应
林肯少年时和他的兄弟在肯塔基老家的一个农场里犁玉米地,林肯吆马,他兄弟扶犁,而那匹马很懒,慢慢腾腾,走走停停。可是有一段时间马走得飞快。 林肯感到奇怪,到了地头,他发现有一只很大的马蝇叮在马身上,他就把马蝇打落了。看到马蝇被打落了,他兄弟就抱怨说:”哎呀,你为什么要打掉它,正是那家伙使马跑起来的嘛!” 在你心满意足的时候,去寻找你的马蝇。没有firefox,不会有ie7,firefox就是微软的马蝇之一。马蝇不可怕,怕的是会一口吃掉你的东西,像 ie当初对网景干的那样。
2.最高气温效应
每天最热总是下午2 时左右,我们总认为这个时候太阳最厉害,其实这时的太阳早已偏西,不再是供给最大热量的时候了。此时气温之所以最高,不过是源于此前的热量积累。
你今天的网站流量,是你一个星期或更长时间前所做的事带来的。
3.超限效应(溢出效应)
刺激过多、过强和作用时间过久而引起心理极不耐烦或反抗的心理现象,称之为“超限效应”。 别到别人论坛里发太多广告。别在自己网站上放太多广告。别在自己的论坛里太多地太明显地诱导话题。
4.懒蚂蚁效应
生物学家研究发现,成群的蚂蚁中,大部分蚂蚁很勤劳,寻找、搬运食物争先恐后,少数蚂蚁却东张西望不干活。当食物来源断绝或蚁窝被破坏时,那些勤快的蚂蚁一筹莫展。“懒蚂蚁”则“挺身而出”,带领众伙伴向它早已侦察到的新的食物源转移。 不要把注意力仅仅放在一个网站上,即使这个网站现在为你带来一切。你要给自己一些时间寻找新的可行的方向,以备万一。
5.长尾理论
ChrisAnderson认为,只要存储和流通的渠道足够大,需求不旺或销量不佳的产品共同占据的市场份额就可以和那些数量不多的热卖品所占据的市场份额相匹敌甚至更大。 对于搜索引擎,未必你需要一个热门词排在第一位,如果有一千个冷门词排在第一位,效果不但一样,还会更稳定更长远。
6.破窗理论
栋建筑上的一块玻璃,又没有及时修好,别人就可能受到某些暗示性的纵容,去打碎更多的玻璃。 管理论坛时,如果你发现第一个垃圾贴,赶紧删掉他吧。想想:落伍现在为什么那么多××贴?现在控制比最初控制难多了。
7.“羊群效应”,又称复制原则(Copy Strategy)
一个羊群(集体)是一个很散乱的组织,平时大家在一起盲目地左冲右撞。如果一头羊发现了一片肥沃的绿草地,并在那里吃到了新鲜的青草,后来的羊群就会一哄而上,争抢那里的青草,全然不顾旁边虎视眈眈的狼,或者看不到其它地方还有更好的青草。
不要轻易跟风,保持自己思考的能力。
8.墨菲定律
如果坏事情有可能发生,不管这种可能性多么小,它总会发生,并引起最大可能的损失。
除非垃圾站,否则不要作弊,对搜索引擎不要,对广告也不要。
9.光环效应
人们对人的某种品质或特点有清晰的知觉,印象比较深刻、突出, 这种强烈的知觉, 就像月晕形式的光环一样,向周围弥漫、扩散,掩盖了对这个人的其他品质或特点的认识。
不要轻易崇拜一个人或者公司、一个概念、一种做法。
10.蝴蝶效应
一只亚马逊河流域热带雨林中的蝴蝶,偶尔扇动几下翅膀,两周后,可能在美国德克萨斯州引起一场龙卷风。
不管你做什么,网站或者其他,你都应该关注新闻。机遇或者灾难可能就在那。
11.阿尔巴德定理
一个企业经营成功与否,全靠对顾客的要求了解到什么程度。 我赞同别人的点评:看到了别人的需要,你就成功了一半;满足了别人的需求,你就成功了全部。尤其是做网站。
12.史密斯原则
如果你不能战胜他们,你就加入到他们之中去。
不要试图做孤胆英雄。如果潮流挡不住,至少,你要去思考为什么。
Having recieved a number of requests for a tutorial of sorts on developing Internet Explorer Toolbars with the RBDeskband and CWindowImpl wizards that I created, I have come up with a simple sample toolbar which can be used as a reference when developing your own toolbars or explorer bars. The tutorial will walk you through the stages of developing a toolbar for IE that is very similar to the Address bar that is already present in IE. 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 IE toolbar to get stock quote information from The Motley Fool website. So with that, let us get started.
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:
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.
We will not work through the steps in creating the shell for our toolbar.
Now that we have our project container we need to add our IDeskBand derived component so that the DLL actually exposes something.
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.
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.
We need to create a derived class from the standard EDIT button window class because we are going to be adding methods to our class to help support functionality of the toolbar. This is one reason why we cannot use a CContainedWindow object directly.
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.
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.
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.
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.
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.
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 web browser in which the toolbar is located, create the buttons and place the child windows 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.
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.
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.
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.
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.
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();}
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.
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.
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.
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.
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.
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.
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.
Other popular ATL articles:
|
Tags: class, java, javascript, server, shell, web, windows
本文例子代码下载(19K)(codeproject.com)
在这篇指南的第一部分,我给了大家一个编写外壳扩展的介绍,并且演示了一个一次操作一个简单文件的上下文菜单扩展。在第二部分中,我将要演示如何在一个操作中操作多个文件。这个扩展是一个注册和卸载COM服务器的实用工具。它还演示了如何使用ATL对话框类CDialogImpl。我将通过解释一些特殊的注册表键来讲第二部分,通过这些键你可以使你的扩展被任何文件调用,而不是那些预先选择的类型(.TXT)。
第二部分假设你已经阅读了第一部分,所以你知道了上下文菜单扩展的基本知识。除此之外,你还必须理解COM,ATL和STL的基本知识。
这个外壳扩展将使你注册和卸载那些在EXE,DLL和OCX里的COM服务器。不像我们在第一部分所做的那样,这个扩展将对所有你右键点击事件发生时所有选中的文件进行操作。
运行AppWizard ,做一个新的ATL COM wizard app。我们叫它DllReg。在向导中保持所有默认选项,单击完成。我们现在就有了一个空的将会生成DLL的ATL项目,但是我们必须添加自己的外壳扩展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()将执行如下步骤:
LoadLibrary()加载它; LoadLibrary()成功,看该文件是否有DllRegisterServer()和DllUnregisterServer()的函数出口; 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方法。和以前一样,你需要添加IContextMenu到CDllRegShlExt实现的接口列表中。再一次的,做这些的步骤在第一部分中。
我们将添加两个菜单项到菜单中,一个为注册选中的文件,一个是卸载它们。这些项看起来如下:

我们的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 server(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 shell 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()]或者操作符[像++]。)这些遍历器被分别地赋给it和itEnd。 这个循环一直进行着,直到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文件的格式,以及关键词NoRemove和ForceRemove在第一部分已经解释过了,如果你忘了他们的意思的话。
正如我们前一个扩展一样,在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/
Tags: class, server, shell, windows, 测试, 类, 缓存
第一部分包括了对外壳扩展的概要的介绍,并提供了一个上下文菜单扩展的例程来使你对以后的部分中充满兴趣。
这有两部分,外壳和扩展(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的文件设置一个钩子,这样当用户右键单击一个文本文件的时候,我们的扩展就能被调用了。
好了,现在是我们开始的时候了。那是什么?我还没有告诉你如何使用神秘的外壳扩展接口?不要担心,我将在接下来的过程中为你解释。我发现如果一个概念被解释,有一个例子更容易明白,通过例子代码你很快就能理解。我将会先解释任何东西,然后给出代码,但是我发现还是不容易吸收。总之,启动你的MSVC吧,我们要开始了。
运行AppWizard ,做一个新的ATL COM wizard app。我们叫它SimpleExt 。在向导中保持所有默认选项,单击完成。我们现在就有了一个空的将会生成DLL的ATL项目,但是我们必须添加自己的外壳扩展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>
class 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个菜单项目分别使用命令ID为5、7和8。它的返回值将是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或者2。uFlags是另一个标志组。我将会在后面进行描述。我们可以忽略pwReserved。pszName 是一个指向一个被外壳所拥有的缓存的指针,该缓存保存被显示的帮助字符串。cchMax 是缓存的大小。返回值是HRESULT常量,例如S_OK或E_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函数中。在上面的代码中,我使用了T2CW和T2CA 分别将TCHAR字符串转换为Unicode和ANSI。在函数头部的USES_CONVERSION 宏声明了一个变换宏使用的局部变量。
一个需要注意的重要事项是lstrcpyn()API函数保证了目标字符串是以null结束的。这是它和CRT函数strncpy()的不同之处。如果源字符串的长度大于或等于cchMax时, strncpy() 并不添加结束符null。我建议你总是使用lstrcpyn(),这样你就不用不得不在strncpy()之后添加检查来保证字符串是null结束的。
最后一个IContextMenu方法是InvokeCommand()。这个方法将在用户单击我们添加的那个菜单项目时被调用。它的原型如下:
HRESULT IContextMenu::InvokeCommand ( LPCMINVOKECOMMANDINFO pCmdInfo );
CMINVOKECOMMANDINFO 结构里有很多的信息,但是根据我们现在的意图,我们只需要关心lpVerb和hwnd 。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 ,那个键的默认值是这个名称被保存的地方。这就两个侧面效果:
HKCR\.txt键的默认值,所有存在的外壳扩展都将会停止工作。 看起来,这的确是我设计的缺陷。我想微软也在考虑同样的事,因为最近创建的扩展,像QueryInfo扩展,是在.txt键下注册的。
好了,说明到这儿。有一个最终的注册细节。在Win NT/2000下,我们必须自己将我们的扩展方到一个“被认可的”扩展列表当中。如果我们不这么做的话,那些非管理员用户将不会壮在我们的扩展。这个列表被保存在:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved
在这个键下,我们创建一个字符串值它的名称是我们的GUID。字符串的内容可以是任何东西。做这些事情的代码在我们的DllRegisterServer()和DllUnregisterServer()函数当中。我并不想把这些呆马列在这儿,因为这只是简单的注册表访问。你可以从本文的例子项目当中找到它们。
最终,你写成了这个相当不容易的扩展,然后你将会调试它。打开你的项目设置(Project->Settings),到Debug栏,在"Executable for debug session"编辑框中输入资源管理器的全路径,例如:"C:\windows\explorer.exe"。如果你使用的是NT或2000,而且你已经设置过了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/ 找到。例子代码,原文也可以从那儿找到。我的email是mefish@163.net,头一次翻译,做得不好,任何意见、建议、鲜花、掌声、石头、带酒的啤酒瓶都将受到热烈欢迎……
Tags: class, debug, ror, server, shell, windows, 开发, 类, 缓存
定制浏览器
作者:冯明德
浏览器控件是个典型的Active控件,提供了大量的接口及自动化对象,可以灵活的加以控制,需要的时候,可以通过这些接口控制浏览器的行为,或提供相应的出接口定制浏览器。
一、概述
浏览器对象CLSID:
CLSID_WebBrowser
提供的主要接口
IWebBrowser2 浏览器的接口
当文档建立后,可以得到相应的文档接口,文档中各标记元素的接口。
在DHTML中,大量的对象和事件就是又这些接口提供和管理的。
IHTMLDocument2
IHTMLWindow2
IHTMLEventObj
IHTMLElement
….
浏览器还将调用宿主提供的接口,以发出事件或给用户提供定制机会。
出接口
DIID_DWebBrowserEvents2
DIID_HTMLDocumentEvents
DIID_HTMLWindowEvents
(ICustomDoc)
IDocHostUIHandler
二、事件的相应
除了使用MFC缺省的事件响应机制外,也可以自建事件接受器,来响应事件
也就是,在封装对象中提供DIID_DWebBrowserEvents2 接口,然后将此接口作为接受器连接到浏览器对象。
一种做法是
在派生类中,使用MFC建立接口方案提供一个DIID_DWebBrowserEvents2接口对象嵌套成员。
class CFMDBrowser : public CWebBrowser{ ... //事件接收器接口 //DWebBrowserEvents //这是一个IDispatch分发接口 BEGIN_INTERFACE_PART(BrowserEventSink,DWebBrowserEvents) STDMETHOD(GetTypeInfoCount)(UINT *pctinfo); STDMETHOD(GetTypeInfo)(UINT iTInfo,LCID lcid,ITypeInfo **ppTInfo); STDMETHOD(GetIDsOfNames)(REFIID riid, LPOLESTR *rgszNames,UINT cNames, LCID lcid,DISPID *rgDispId); STDMETHOD(Invoke)(DISPID dispIdMember,REFIID riid,LCID lcid, WORD wFlags,DISPPARAMS *pDispParams, VARIANT *pVarResult,EXCEPINFO *pExcepInfo, UINT *puArgErr); END_INTERFACE_PART(BrowserEventSink) DWORD m_dwEventSinkCookie; ...}
这是一个接收器接口,无需添入到对象的接口表中。
(无需:BEGIN_INTERFACE_MAP、END_INTERFACE_MAP)
这是一个以分发接口(IDispatch)作为出接口的典型例子。在接口函数的实现中。Invoke负责又分发ID调用不同的虚拟函数。(事件函数作为虚拟函数,供派生类重载)
STDMETHODIMP CFMDBrowser::XBrowserEventSink::Invoke(DISPID dispIdMember,REFIID riid,LCID lcid, WORD wFlags,DISPPARAMS *pDispParams, VARIANT *pVarResult,EXCEPINFO *pExcepInfo, UINT *puArgErr){ METHOD_PROLOGUE(CFMDBrowser,BrowserEventSink) //将事件分发到各虚拟函数 //分发ID的定义见 exdispid.h switch(dispIdMember) { case DISPID_BEFORENAVIGATE: ... HRESULT hr=pThis->OnBeforeNavigate(..) //事件对应的虚拟函数 ... break; case DISPID_NAVIGATECOMPLETE: ... case ... case ...}
建立与浏览器的连接
得到IConnectionPointContainer接口,查找与DIID_DWebBrowserEvents对应的接收器,建立连接,记录连接的标号(m_dwEventSinkCookie);
BOOL CFMDBrowser::Connect(){ IUnknown *p_Unk=GetControlUnknown(); if(p_Unk==NULL) return FALSE; BOOL bOK=FALSE; //查找连接点对象 IConnectionPointContainer *i_cpc=0; HRESULT hr=p_Unk->QueryInterface(IID_IConnectionPointContainer, (void **)(&i_cpc)); if (SUCCEEDED(hr)) { IConnectionPoint *i_cp=0; hr=i_cpc->FindConnectionPoint(DIID_DWebBrowserEvents,&i_cp); if (SUCCEEDED(hr)) { hr=i_cp->Advise(&m_xBrowserEventSink,&m_dwEventSinkCookie); i_cp->Release(); bOK=TRUE; } i_cpc->Release(); } return bOK;}
结束时,断开与浏览器的连接
BOOL CFMDBrowser::DisConnect(){ IUnknown *p_Unk=GetControlUnknown(); if(p_Unk==NULL) return FALSE; BOOL bOK=FALSE; //查找连接点对象 IConnectionPointContainer *i_cpc=0; HRESULT hr=p_Unk->QueryInterface(IID_IConnectionPointContainer, (void **)(&i_cpc)); if (SUCCEEDED(hr)) { IConnectionPoint *i_cp=0; hr=i_cpc->FindConnectionPoint(DIID_DWebBrowserEvents,&i_cp); if (SUCCEEDED(hr)) { hr=i_cp->Unadvise(m_dwEventSinkCookie); i_cp->Release(); bOK=TRUE; } i_cpc->Release(); } return bOK;}
三、定制浏览器UI
浏览器提供了IDocHostUIHandler出接口,向用户查询界面特性
可以提供这个接口,与浏览器连接上,在其实现中,定制界面
1.建立接口
class CFMDBrowser : public CWebBrowser{ ... //IDocHostUIHandler接口,控制浏览器界面 BEGIN_INTERFACE_PART(UIHandlerSink,IDocHostUIHandler) STDMETHOD(ShowContextMenu)(DWORD,POINT*,IUnknown*,IDispatch*); STDMETHOD(GetHostInfo)(DOCHOSTUIINFO*); STDMETHOD(ShowUI)(DWORD, IOleInPlaceActiveObject*, IOleCommandTarget*, IOleInPlaceFrame*, IOleInPlaceUIWindow*); STDMETHOD(HideUI)(); STDMETHOD(UpdateUI)(); STDMETHOD(EnableModeless)(INT); STDMETHOD(OnDocWindowActivate)(INT); STDMETHOD(OnFrameWindowActivate)(INT); STDMETHOD(ResizeBorder)(LPCRECT,IOleInPlaceUIWindow*,INT); STDMETHOD(TranslateAccelerator)(LPMSG,const GUID*,DWORD); STDMETHOD(GetOptionKeyPath)(LPOLESTR*,DWORD); STDMETHOD(GetDropTarget)(IDropTarget*,IDropTarget**); STDMETHOD(GetExternal)(IDispatch**); STDMETHOD(TranslateUrl)(DWORD,OLECHAR*,OLECHAR**); STDMETHOD(FilterDataObject)(IDataObject*,IDataObject**); END_INTERFACE_PART(UIHandlerSink) ...}
无需添加接口映射
2.连接到浏览器
需要在NavigateComplete时间发生后,得到
ICustomDoc接口,由此接口的
SetUIHandler成员设置UI接口。
//设置界面接口IDispatch *i_dispatch=0;if (SUCCEEDED(i_dispatch=pThis->GetDocument())){ IHTMLDocument2 *i_htmldoc2=0; if (SUCCEEDED(i_dispatch->QueryInterface(IID_IHTMLDocument2, (void **)(&i_htmldoc2)))) { // force connection of IDocHostUIHandler ICustomDoc *i_customdoc=0; if (SUCCEEDED(i_htmldoc2->QueryInterface( IID_ICustomDoc, (void **)(&i_customdoc)))) { i_customdoc->SetUIHandler( &(pThis->m_xUIHandlerSink)); i_customdoc->Release(); } } i_dispatch->Release();}
3.在接口的实现中,控制用户界面
例如更改右键菜单
在STDMETHOD(ShowContextMenu)(DWORD,POINT*,IUnknown*,IDispatch*);
的实现中:
HRESULT CFMDBrowser::ShowContextMenu(DWORD,POINT*,IUnknown*,IDispatch*){ ..建立自己的菜单 return S_OK; }
关键字:Band,Desk Band,Explorer Band,Tool Band,浏览器栏,工具栏,桌面工具栏
一、引言
最近,由于工作的要求,我需要在 IE 上做一些开发工作。于是在 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 对象,从 Shell 4.71(IE 5.0) 开始提供支持。Band 是一个 COM 对象,必须放在一个容器中去使用,当然使用它们就好象使用普通窗口是一样的。IE 就是一个容器,桌面 Shell 也是一个容器,它们提供不同的函数功能,但基本的实现是相似的。
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)显示了一个 HTML 文件,并且实现了对 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 实现这个接口很简单:
class 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 的命令有:
| 值 | 描述 |
|---|---|
| pUnk | band 对象的 IUnknown 指针,其它的桌面 bands 将被隐藏 |
| 0 | 隐藏所有的桌面 bands |
| 1 | 显示所有的桌面 bands |
3.4 Band 对象注册
Band 对象必须注册为一个 OLE 进程内的服务器,并且支持 apartment 线程公寓。注册表中默认键的值是表示菜单的文字。对于浏览器栏,它加到 IE 菜单的“查看\浏览器栏”中;对于工具栏 band ,它加到 IE 菜单的“查看\工具栏”中;对于桌面 band, 它加到系统任务栏的快捷菜单中。在菜单资源中,可以使用“&”指明加速键。
通常,一个基本的 band 对象的注册表项目是:
HKEY_CLASSES_ROOT
CLSID
{你的 band 对象的 CLSID}
(Default) = 菜单的文字
InProcServer32
(Default) = DLL 的全路径文件名
ThreadingModel= Apartment
工具栏 bands 还必须把它们的 CLSID 注册到 IE 的注册表中。
在 HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\Toolbar 下给出 CLSID 作为键名,而其键值是被忽略的。
HKEY_LOCAL_MACHINE
Software
Microsoft
Internet Explorer
Toolbar
{你的 band 对象的 CLSID}
还有几个可选的注册表项目(例子程序并不是这样实现的)。比如,你想让浏览器栏显示 HTML 的话,必须要如下设置注册表:
HKEY_CLASSES_ROOT
CLSID
{你的 Band 对象的 CLSID}
Instance
CLSID
(Default) = {4D5C8C2A-D075-11D0-B416-00C04FB90376}
同时,如果要指定一个本地的 HTML 文件,那么要如下设置:
HKEY_CLASSES_ROOT
CLSID
{你的 Band 对象的 CLSID}
Instance
InitPropertyBag
Url
另外,还可以指定浏览器栏的宽和高,当然,它是依赖于这个栏是纵向还是横向的。其实这个项目无所谓,因为当用户调整了浏览器栏的大小后,会自动保存在注册表中的。
HKEY_CURRENT_USER
Software
Microsoft
Internet Explorer
Explorer Bars
{你的 Band 对象的 CLSID}
BarSize
BarSize 键的类型必须是 REG_BINARY 类型,它有8个字节。左起前4个字节,是用16进制表示的像素宽度或高度,后4个字节保留,你应该设置为0。下面是一个可以在浏览器栏上显示 HTML 文件的全部注册表项目的例子,默认宽度为291(0×123)个像素点:
HKEY_CLASSES_ROOT
CLSID
{你的 Band 对象的 CLSID}
(Default) = 菜单文字
InProcServer32
(Default) = DLL 的全路径文件名
ThreadingModel= Apartment
Instance
CLSID
(Default) = {4D5C8C2A-D075-11D0-B416-00C04FB90376}
InitPropertyBag
Url= 你的 HTML 文件名
HKEY_CURRENT_USER
Software
Microsoft
Internet Explorer
Explorer Bars
{你的 Band 对象的 CLSID}
BarSize= 23 01 00 00 00 00 00 00
对于注册表的设置,用 ATL 实现其实是异常简单的。打开工程的 xxx.rgs 文件,并手工编辑一下就可以了。 下面这个文件源码,是例子程序中 IE 工具栏的注册表样式,HKLM 是需要手工添加的,因为它不使用组件类型方式注册。而对于其它类型的 band 对象只要在类声明中添加:
BEGIN_CATEGORY_MAP(Cxxx) // 向注册表中注册 COM 类型 IMPLEMENTED_CATEGORY(CATID_InfoBand) // 垂直样式的浏览器栏END_CATEGORY_MAP()
IE 工具栏类型 band 对象的“.rgs”文件
HKCR // 这个项目是 ATL 帮你生成的,你只要手工修改“菜单上的文字”就可以了{ Bands.ToolBar.1 = s ''ToolBar Class'' { CLSID = s ''{ 你的 CLSID }'' } Bands.ToolBar = s ''ToolBar Class'' { CLSID = s ''{ 你的 CLSID }'' CurVer = s ''Bands.ToolBar.1'' } NoRemove CLSID { ForceRemove { 你的 CLSID } = s ''用在菜单上的文字(&T)'' { ProgID = s ''Bands.ToolBar.1'' VersionIndependentProgID = s ''Bands.ToolBar'' ForceRemove ''Programmable'' InprocServer32 = s ''%MODULE%'' { val ThreadingModel = s ''Apartment'' } ''TypeLib'' = s ''{xxxx-xxxx-xxxxxxxxxxxxxxx}'' } }}HKLM // 这个项目是手工添加的IE工具栏所特有的{ Software { Microsoft { ''Internet Explorer'' { NoRemove Toolbar { ForceRemove val { 你的 CLSID } = s ''随便给个说明性文字串'' } } } }}
四、 ATL 实现
下载代码后(VC 6.0 工程),请参照前面的说明仔细阅读,代码中也有一些关键点的注释。如果想运行,则可以用 regsvr32.exe 进行注册,然后打开 IE 浏览器或资源浏览器就可以看到效果了。如果想自己实践一下,可以按照如下的步骤构造工程:
4.1 建立一个 ATL DLL 工程
4.2 添加 New ATL Object…,选择 Internet Explorer Object,选这个类型的目的是让向导给我们添加 IObjectWithSite 的支持。如果你使用的是 .net 环境,则不要忘记选择支持这个接口。

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

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

4.5 展现你无穷的智慧,开始输入程序吧。如果是 Debug 方式编译,可能会出现一个连接错误,报告找不到_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 就会加载活动的桌面对象。
五、结束语
好了,到这里,就到这里了。祝大家学习快乐^_^
Tags: class, debug, html, server, shell, web, windows, 开发, 类
我……无语…….绝了……..高人……..偶像………/(-__-)/ 服了~
1:救到女主角后回到小村子。教堂右侧有个高塔,男主角先上去,到顶后立刻回身跳下去。这时女主角会跟爬上后就傻傻的站着不动。不要犹豫,换上狙击放大看吧!

2:在后面男女主角走到一段缆车前,练枪过后会到达另一头。下了铁梯,有个山洞,男主角先进去把里面的3个宝宝洗白。上2层开宝,然后召唤女主角上来。同样方法,再看到女主角爬梯子后跳下。同样女主角回站着不动,换出狙击。天啊!!那短裙~~~在~~~在随风飘动。(本人最爱这一段,太刺激了。同样也是看的最清晰的一段)
3:这里~~~就看各位大大的技术了。在把最终BOSS强暴了之后男主角带领女主角逃离。路上有一个大断层,男主角毫不犹豫的跳下后老动作,换狙偷窥。看着时间一点点过去,男主角还在欣赏迷人的风景。这让本人有种化身为神的感觉。
Tags: 技术
有效的减肥方法应该是对身体健康有所帮助的,养成了这些健康的习惯长期坚持,一定会有好收获!
行动一:细嚼慢咽享受每一口食物
细嚼慢咽不单只是淑女的象征,它也是减肥的小秘诀。一口咀嚼 20 下,不但可以吃得高兴,更可以体会到吃的趣味。
行动二:早晨喝一杯温开水
行动三:不要边看电视边吃饭
边吃饭边看电视虽然很轻松悠闲,但很容易在不知不觉中吃下过量的食物。
行动四:在碗中留下一小口的食物
餐后,在碗中留下一小口食物,然后看着食物心中默念: “ 我已经饱啰,真的吃不下了。 ” 用心理来克制欲望,慢慢练习,以后就不容易贪吃啰。
行动五:遵行下午3点下午茶时间
行动六:饭前喝汤、吃水果
中国人习惯饭后喝汤和吃水果,其实是不好的,这样只会让你的胃被撑大,如果将喝汤和吃水果放在饭前进行,你在用餐时就可以少吃一点了。
行动七:吃丰富的早餐
“ 早餐一定要吃喔! ” 这不是广告词,而是真的,别以为不吃早餐可以减肥,其实一顿丰富的早餐会让你一整天都精神百倍。不吃早餐只会消耗你的肌肉而不是脂肪,还会使你整天昏昏沉沉的。
行动八:改喝低脂鲜奶
天天喝鲜奶真的很不错,但是不妨改为喝低脂鲜奶,因为它的热量是全脂鲜奶的一半,但钙质与蛋白质却相同。
行动九:提早刷牙可以避免吃宵夜
晚上提早刷牙,清新的口气会让你抑制住而不吃宵夜。
行动十:洗澡后30分钟做按摩
每天抽空泡个热水澡,可以松弛紧张的神经。热水浴后30分钟是最佳的瘦身时机,用塑身霜在需要雕塑的身体部位以打圈的方式涂抹,每次20分钟,不但有润肤作用,还可有效去除角质。
Tags: class