01

Internet Explorer Toolbar (Deskband) Tutorial


转至http://www.codeproject.com

The Motley Fool Quote IE Toolbar

Introduction

Having recieved a number of requests for a tutorial of sorts on developing Internet Explorer Toolbars with the RBDeskband and CWindowImpl wizards that I created, I have come up with a simple sample toolbar which can be used as a reference when developing your own toolbars or explorer bars. The tutorial will walk you through the stages of developing a toolbar for 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.

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,浏览器栏,工具栏,桌面工具栏

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

Band 样式

组件类型

CATID

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

HKEY_CLASSES_ROOT
CLSID
{你的 band 对象的 CLSID}

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

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

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

HKEY_LOCAL_MACHINE
Software
Microsoft
Internet Explorer
Toolbar

  {你的 band 对象的 CLSID}

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

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

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

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

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

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

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

HKEY_CLASSES_ROOT
CLSID
{你的 Band 对象的 CLSID}

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

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

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

  BarSize= 23 01 00 00 00 00 00 00

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

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

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

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

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

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

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

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

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

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

0

PHP5 效率优化


静态调用的成员一定要定义成 static  (5 ONLY)

PHP 5 引入了静态成员的概念,作用和 PHP 4 的函数内部静态变量一致,但前者是作为类的成员来使用。静态变量和 的类变量( variable)差不多,所有类的实例共享同一个静态变量。

<?php
class foo
{
    function
bar
() {
        echo
‘foobar’
;
    }
}

$foo = new foo;

// instance way

$foo->bar();

// static way

foo::bar();
?>

静态地调用非 static 成员,效率会比静态地调用 static 成员慢 50-60%。主要是因为前者会产生 E_STRICT 警告,内部也需要做转换。

使用类常量 (PHP5 ONLY)

PHP 5 新功能,类似于 C++ 的 const。

使用类常量的好处是:

- 编译时解析,没有额外开销
- 杂凑表更小,所以内部查找更快
- 类常量仅存在于特定「命名空间」,所以杂凑名更短
- 代码更干净,使除错更方便

(暂时)不要使用 require/include_once

require/include_once 每次被调用的时候都会打开目标文件!

- 如果用绝对路径的话,PHP 5.2/6.0 不存在这个问题
- 新版的 APC 缓存系统已经解决这个问题

文件 I/O 增加 => 效率降低

如果需要,可以自行检查文件是否已被 require/include。

不要调用毫无意义的函数

有对应的常量的时候,不要使用函数。

<?php
php_uname
(‘s’) == PHP_OS
;
php_version() == PHP_VERSION
;
php_sapi_name() == PHP_SAPI
;
?>
虽然使用不多,但是效率提升大概在 3500% 左右。

最快的 Win32 检查

<?php
$is_win
= DIRECTORY_SEPARATOR == ‘\\’
;
?>

- 不用函数
- Win98/NT/2000/XP/Vista/Longhorn/Shorthorn/Whistler…通用
- 一直可用

时间问题 (PHP>5.1.0 ONLY)

你如何在你的软件中得知现在的时间?简单,「time() time() again, you ask me…」。

不过总归会调用函数,慢。

现在好了,用 $_['REQUEST_TIME'],不用调用函数,又省了。

加速 PCRE

 对于不用保存的结果,不用 (),一律用 (?:)

这样 PHP 不用为符合的内容分配内存,省。效率提升 15% 左右。

- 能不用正则,就不用正则,在分析的时候仔细阅读手册「字符串函数」部分。有没有你漏掉的好用的函数?

加速 strtr

如果需要转换的全是单个字符的时候,用字符串而不是数组来做 strtr:

<?php
$addr
= strtr($addr, "abcd", "efgh");
// good
$addr = strtr($addr, array(‘a’ => ‘e’
,
                           
// …
                           
));
// bad
?>

效率提升:10 倍。

不要做无谓的替换

即使没有替换,str_replace 也会为其参数分配内存。很慢!解决办法:

- 用 strpos 先查找(非常快),看是否需要替换,如果需要,再替换

效率:

- 如果需要替换:效率几乎相等,差别在 0.1% 左右。
- 如果不需要替换:用 strpos 快 200%。

邪恶的 @ 操作符

不要滥用 @ 操作符。虽然 @ 看上去很简单,但是实际上后台有很多操作。用 @ 比起不用 @,效率差距:3 倍。

特别不要在循环中使用 @,在 5 次循环的测试中,即使是先用 error_reporting(0) 关掉错误,在循环完成后再打开,都比用 @ 快。

善用 strncmp

当需要对比「前 n 个字符」是否一样的时候,用 strncmp/strncasecmp,而不是 substr/strtolower,更不是 PCRE,更千万别提 ereg。strncmp/strncasecmp 效率最高(虽然高得不多)。

慎用 substr_compare (PHP5 ONLY)

按照上面的道理,substr_compare 应该比先 substr 再比较快咯。答案是否定的,除非:

- 无视大小写的比较
- 比较较大的字符串

不要用常量代替字符串

为什么:

- 需要查询杂凑表两次
- 需要把常量名转换为小写(进行第二次查询的时候)
- 生成 E_NOTICE 警告
- 会建立临时字符串

效率差别:700%。

不要把 count/strlen/sizeof 放到 for 循环的条件语句中

贴士:我的个人做法

<?php
for ($i = 0, $max = count($array);$i < $max; ++$i
);
?>

效率提升相对于:

- count 50%
- strlen 75%

短的代码不一定快

<?php
// longest
if ($a == $b
) {
   
$str .= $a
;
} else {
   
$str .= $b
;
}

// longer
if ($a == $b
) {
   
$str .= $a
;
}
$str .= $b
;

// short
$str .= ($a == $b ? $a : $b
);
?>

你觉得哪个快?

效率比较:

- longest: 4.27
- longer: 4.43
- short: 4.76

不可思议?再来一个:
<?php
// original
$d = dir(‘.’
);
while ((
$entry = $d->read()) !== false
) {
    if (
$entry == ‘.’ || $entry == ‘..’
) {
        continue;
    }
}

// versus
glob(‘./*’
);

// versus (include . and ..)
scandir(‘.’
);
?>

哪个快?

效率比较:

- original: 3.37
- glob: 6.28
- scandir: 3.42
- original without OO: 3.14
- SPL (PHP5): 3.95

画外音:从此也可以看出来 PHP5 的面向对象效率提高了很多,效率已经和纯函数差得不太多了。

提高 PHP 文件访问效率

需要包含其他 PHP 文件的时候,使用完整路径,或者容易转换的相对路径。

<?php

include ‘file.php’; // bad approach

incldue ‘./file.php’; // good

include ‘/path/to/file.php’; // ideal

?>

物尽其用

PHP 有很多扩展和函数可用,在实现一个功能的之前,应该看看 PHP 是否有了这个功能?是否有更简单的实现?

<?php
$filename
= "./somepic.gif"
;
$handle = fopen($filename, "rb"
);
$contents = fread($handle, filesize($filename
));
fclose($handle
);

// vs. much simpler

file_get_contents(‘./somepic.gif’);
?>

关于引用的技巧

引用可以:

- 简化对复杂结构数据的访问
- 优化内存使用
<?php
$a
['b']['c'
] = array();

// slow 2 extra hash lookups per access
for ($i = 0; $i < 5; ++$i
)
   
$a['b']['c'][$i] = $i
;

// much faster reference based approach
$ref =& $a['b']['c'
];
for (
$i = 0; $i < 5; ++$i
)
   
$ref[$i] = $i
;
?>

<?php
$a
= ‘large string’
;

// memory intensive approach
function a($str
)
{
    return
$str.‘something’
;
}

// more efficient solution
function a(&$str
)
{
   
$str .= ‘something’
;
}
?>

==============================================
参考资料
http://ilia.ws

Ilia 的个人网站,,他参与的开发以及出版的一些稿物链接等等。
http://ez.no

eZ components 官方网站,eZ comp 是针对 PHP5 的开源通用库,以效率为己任,Ilia 也参与了开发。
http://phparch.com

php|architect,不错的 php 出版商/培训组织。买不起或者买不到的话,网上可以下到很多经典的盗版。

http://talks.php.net

0

免费软件套装


在 CB 上看到的……

办公

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

解压缩

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

互联网

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

P2P

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

聊天

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

安全

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

网络

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

服务器

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

音频

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

视频

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

图像

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

3D

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

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

CD/DVD

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

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

系统工具

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

UI设计

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

硬件检测

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

游戏

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

教育

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

杂类

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

墙纸

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

0

活学活用Windows Server 2003分区增容功能


分区增容就是当一个分区的空间不能满足使用需求时,为其额外加大空间的方法。很多朋友遇到这种情况时,一般都使用PartitionMagic完成的。但实际上,使用Windows XP/ 2003的用户完全可以使用系统内置的磁盘管理功能来完成分区的空间“增容”。下面我们以实例的方式来探讨一下。

  一、划出自由空间

假设现在需要对D盘增容50MB的空间,这个空间需要从E盘上提取。那么首先要就从E盘上划分出这50MB的空间才行。这个操作的过程如下:

  首先将E盘所有数据转移到其它分区,然后单击“开始→运行”,输入“Diskmgmt.msc”后回车,打开“磁盘管理”窗口。选中E盘并点击右键,在弹出的快捷菜单中选择“删除此逻辑驱动器”项。在弹出的提示框中点击“是”按钮继续。操作完毕后,将会在“磁盘0”列中出现与删除分区相同大小的可用空间。

  二、给分区增容

  此时请注意D盘当前空间为855MB,现在我们来进行为其增加50MB的操作。单击“开始→程序→附件→命令提示符”,在打开的窗口中依次输入“Diskpart”、“List volume”、“Select volume 2”、“Extend Size=50”四条命令。

  其中,“Diskpart”命令用来调用DOS磁盘管理程序,“Diskpart/?”命令可以看到该命令的DOS下中文帮助信息。“List Volume”用于显示系统上所有磁盘的详细信息,从而得知所需扩充分区的卷号。这里可以看出D盘的卷号为“2”;“Select Volume 2”命令用于选择卷,这里根据上一步得出的提示选择卷2;“Extend Size=50”用于将D盘空间增容,这个增容的来源空间当然是划分出的自由空间了。从命令执行的结果“DiskPart成功地扩展了卷”来看,我们对D盘的空间增容已经成功了。

  最后在“磁盘管理窗口”中选择剩余的可用空间,依次点击“操作→所有任务→新建逻辑驱动器”命令,根据提示为该空间分配驱动器号和进行格式化操作即可。

0

深入Native应用程序


版权所有 1998 Mark Russinovich

 

翻译:MJ0011

最后更新:1998年2月8日

导言

如果你对WindowsNt结构有一定的了解,你可能会知道,Win32应用程序所使用的API,并非是"真正"的NT API

。POSIX,OS/2和Win32,这些WindowsNT操作系统环境,使用他们自己的API同他们的客户应用程序进行交流,

但却使用NT "native" API同 WindowsNT进行交流.这些native API大部分都是未公开的(undocumented)。大

约只有25个API(包含250种功能)在WindowsNT设备驱动开发工具包(Device Driver Kit)里有所描述。

尽管绝大多数人都不知道,但"native"应用程序的确存在与WindowsNT上,他们在操作环境上没有任何客户程

序. 这些程序交流着native nt API并且不能使用任何操作环境API比如 Win32. 为什么这样一种程序是必须

的呢?因为在Win32子系统启动之前(大约在登陆对话框出现时)只可以运行native应用程序.最常见的native

应用程序的例子是"autochk"程序,他在初始化兰色登陆屏幕前运行 chkdsk(程序在屏幕上打印一串".")。

当然,Win32应用程序环境服务程序:CSRSS.exe(客户-服务运行时间子系统),也是一个native应用程序

在这篇文章里,我将会讲述如何构造一个native应用程序以及它们是如何工作的,同时我也会提供一个

native应用程序的示例源代码。这个示例很容易安装,它会在启动时的兰色屏幕打印一段你指定的字符串

Autochk是如何被执行的

Autochk在当内存分页被打开,Windows启动和系统开始驱动被载入之间的时间内运行。在这个时间点 启动顺

序会话管理器(smss.exe)进入windowsNT用户模式,并且没有任何程序被启动
注册表中:HKLM\System\CurrentControlSet\Control\Session Manager\BootExecute
一个MULTI_SZ类型的键值
这里存放着将被会话管理器所执行的程序名称和参数
通常Autochk后加*号作为其参数"

Autocheck Autochk *
;名称 程序名 参数

会话管理器在<winnt>\system32目录下查找该值列出的可执行程序.当Autochk运行时,没有任何文件被打开

,所以Autochk可以用raw模式打开任何一个驱动器卷(包括根驱动器),并操作其磁盘数据结构.之后的任何

时间点都无法进行类似这样的操作

编译Native应用程序
微软没有提供相应的文档,但是NT DDK构建器知道如何去生成一个native应用程序,而且它可以被用来编译

autochk程序.和编写设备驱动程序一样,你必须指定SOURCE文件中的信息来定义应用程序。然而和编写驱动

不同的时,你在SOURCE文件中要求生成一个native应用程序需要这样定义:

TARGETTYPE=PROGRAM

构建器使用一个标准的makefile来进行向导:\ddk\inc\makefile.def 在编译native应用程序时会查找名为

nt.lib的运行库。不幸的是,微软并没在DDK上装载这个文件(在windows  2003 DDK里包括了这个文

件,但是我怀疑你用这个版本来连接你的native应用程序是无法运行在WindowsXP或win2000上的)
不管怎样,你可以忽略这个错误,方法是加入一行不考虑nt.lib,而指定visual c++的运行库msvcrt.lib到

makefile.lib中

如果你在DDK的"Checked Build"环境下进行编译,将会在%BASEDIR%\lib\%CPU%\Checked(例如

c:\ddk\lib\i386\checked\native.exe)产生一个包含了全部调试信息的native应用程序。如果你在"Free 

Build"环境中编译,你会在%BASEDIR%\lib\%CPU%\Free得到一个释出版本的程序.这些和构造设备驱动程序

放置的位置是一样的。

Native应用程序有着".exe"的扩展名,但是你不能象 win32的.exe文件那样去运行它,如果你在WIN32环境

下运行下,将会得到如下提示:

"<应用程序名> 应用程序无法在Win32模式中运行。"

深入学习一个native应用程序

native应用程序的入口点是NtProcessStartup,类似winmain或main.不同于其他的 Win32入口点的是,

native应用程序提供一个数据结构来存放它的唯一的参数来定位命令行参数

大多数的native应用程序的运行环境是由WindowsNt的native API输出库—NTDLL.DLL提供的。native应用

程序必须使用RtlCreateHeap(一个ntdll函数)来创建他们自己的堆来分配存储,使用RtlAllocateHeap来分

配内存以及用RtlFreeHeap来释放内存。native应用程序需要使用NtDisplayString 函数才可以打印想要的

内容到屏幕上(将被输出到初始化时的兰色屏幕上)

Native应用程序不象win32程序那样简单地从他们的启动函数返回,你需要调用NtProcessTerminate函数来

结束它的进程

NTDLL运行包含了数百个函数允许native应用程序执行文件I/O,与设备驱动进行相连,并执行进程间通讯。

不幸的是,他们大部分都是未公开的。

一个native应用程序的例子
我创建一个“玩具”native 应用程序用来演示native应用程序是如何构建的以及他们是如何工作的。运行

install.bat来安装native程序。批处理程序复制native.exe到你的<winnt>\system32目录并在注册表中增

加一个BootExecute的入口点:

native Hello World!

当你重新启动时,会话管理器运行完autochk后就会执行native。native分配一些堆,定位它的命令行参数

并打印参数("Hello world!")到兰色屏幕上,它所使用的函数上面已说过了。如果你想要打印其他的简单内

容,可以编辑BootExecute值使用regedit或regedit32,修改"Hello world"为你想要的信息

运行uinstall.bat可以卸载这个native执行程序。它从<winnt>\system32目录删除native.exe,并修改

BootExecute值为通常的值

如果你想要构建native程序你必须要用Windows设备驱动工具包(DDK),复制makefile.def到 \ddk\inc然后你

可以运行构建

 

=========================================================
Native.H

//======================================================================
//
// Native.h
//
// Mark Russinovich
// http://www.ntinternals.com
//
// This file includes the definitions required by the Native.exe sample
// NT native program to do what it does. 
//
//======================================================================

//
// Environment information, which includes command line and
// image file name
//
typedef struct {
       ULONG            Unknown[21];     
       UNICODE_STRING   CommandLine;
       UNICODE_STRING   ImageFile;
} ENVIRONMENT_INFORMATION, *PENVIRONMENT_INFORMATION;

//
// This structure is passed as NtProcessStartup’s parameter
//
typedef struct {
       ULONG                     Unknown[3];
       PENVIRONMENT_INFORMATION  Environment;
} STARTUP_ARGUMENT, *PSTARTUP_ARGUMENT;

//
// Data structure for heap definition. This includes various
// sizing parameters and callback routines, which, if left NULL,
// result in default behavior
//
typedef struct {
 ULONG     Length;
 ULONG     Unknown[11];
} RTL_HEAP_DEFINITION, *PRTL_HEAP_DEFINITION;

//
// Native NT api function to write something to the boot-time
// blue screen
//
NTSTATUS 
NTAPI 
NtDisplayString(
  PUNICODE_STRING String 
  );

//
// Native applications must kill themselves when done - the job
// of this native API
//
NTSTATUS 
NTAPI 
NtTerminateProcess(
     HANDLE ProcessHandle, 
     LONG ExitStatus 
     );

//
// Definition to represent current process
//
#define NtCurrentProcess() ( (HANDLE) -1 )

//
// Heap creation routine
//
HANDLE 
NTAPI 
RtlCreateHeap(
       ULONG Flags, 
       PVOID BaseAddress, 
       ULONG SizeToReserve, 
       ULONG SizeToCommit, 
       PVOID Unknown,
       PRTL_HEAP_DEFINITION Definition
       );

//
// Heap allocation function (ala "malloc")
//
PVOID 
NTAPI 
RtlAllocateHeap(
  HANDLE Heap, 
  ULONG Flags, 
  ULONG Size 
  );

//
// Heap free function (ala "free")
//
BOOLEAN 
NTAPI 
RtlFreeHeap(
     HANDLE Heap, 
     ULONG Flags, 
     PVOID Address 
     );

=========================================================================
Native.C

//======================================================================
//
// Native.c
//
// Mark Russinovich
// http://www.ntinternals.com
//
// This is a demonstration of a Native NT program. These programs
// run outside of the Win32 environment and must rely on the raw
// services provided by NTDLL.DLL. AUTOCHK (the program that executes
// a chkdsk activity during the system boot) is an example of a
// native NT application.
//
// This example is a native ’hello world’ program. When installed with
// the regedit file associated with it, you will see it print 
// "hello world" on the initialization blue screen during the system
// boot. This program cannot be run from inside the Win32 environment.
//
//======================================================================
#include "ntddk.h" // include this for its native functions and defn’s
#include "stdio.h"
#include "native.h"

//
// Our heap
//
HANDLE Heap;

//———————————————————————-
//
// NtProcessStartup
//
// Instead of a ’main’ or ’winmain’, NT applications are entered via
// this entry point.  
//
//———————————————————————-
void NtProcessStartup( PSTARTUP_ARGUMENT Argument )
{
    PUNICODE_STRING commandLine;
    PWCHAR stringBuffer, argPtr;
    UNICODE_STRING helloWorld;
    RTL_HEAP_DEFINITION  heapParams;

    //
    // Initialize some heap
    //
    memset( &heapParams, 0, sizeof( RTL_HEAP_DEFINITION ));
    heapParams.Length = sizeof( RTL_HEAP_DEFINITION );
    Heap = RtlCreateHeap( 2, 0, 0×100000, 0×1000, 0, &heapParams );

    //
    // Point at command line
    //
    commandLine = &Argument->Environment->CommandLine;

    //
    // Locate the argument
    //
    argPtr = commandLine->Buffer;
    while( *argPtr != L’ ’ ) argPtr++;
    argPtr++;

    //
    // Print out the argument
    //
    stringBuffer = RtlAllocateHeap( Heap, 0, 256 );
    swprintf( stringBuffer, L"\n%s", argPtr );
    helloWorld.Buffer = stringBuffer;
    helloWorld.Length = wcslen( stringBuffer ) * sizeof(WCHAR);
    helloWorld.MaximumLength = helloWorld.Length + sizeof(WCHAR);
    NtDisplayString( &helloWorld );

    //
    // Free heap
    //
    RtlFreeHeap( Heap, 0, stringBuffer );

    //
    // Terminate
    //
    NtTerminateProcess( NtCurrentProcess(), 0 );
}

===========================================================================

Install.bat

@echo off
copy native.exe %systemroot%\system32\.
regedit /s add.reg
echo Native Example Installed

=============================================================================
uinstall.bat

@echo off
del %systemroot%\system32\native.exe
regedit /s remove.reg
echo Native Example Uninstalled

转自:http://hi.baidu.com/mj0011/blog/item/85c0b50f80b1baedab6457de.html

0

Windows TCP/IP 临时、保留和封锁端口行为


转至MSDN

本文介绍 套接字应用程序可用的各种类型的传输控制协议 (TCP) 和用户数据报协议 (UDP) 端口及其在 XP 和 2003 中的范围。

导言

TCP 和 UDP 使用端口号来标识源和目标应用程序。对于典型的客户-服务器协议(例如那些用于 和电子邮件访问的协议),通信是由客户端计算机发起的。服务器应用程序通常监听众所周知的 TCP 或 UDP 端口,它们是由 Internet 号码分配机构 (IANA) 分配的。对于源端口,客户端应用程序通常查询操作系统中已不再由其他应用程序占用的动态分配的 TCP 或 UDP 端口。当应用程序请求而后绑定到一个动态分配的端口时,这就是通常所说的通配绑定。

动态分配的端口也称为临时端口。术语“临时”(短暂)并不表示端口的生存期一定很短。例如,用于超文本传输协议的端口在数据传输完成之后会立即关闭。临时是指,与通常在整个服务器计算机运行期间都保持打开的服务器应用程序端口相比,客户端应用程序端口的生存期相对较短(至多只在应用程序运行期间保持打开)。

客户端计算机使用临时端口而不是众所周知的端口,以防与可能使用众所周知端口的本地服务发生冲突。例如,运行 Microsoft Windows XP 的计算机可能会使用 Internet Explorer,还可能运行 Internet 信息服务 (IIS)。当 Internet Explorer 访问网页时,它无法将 TCP 端口 80 用作源端口,因为该本地端口可能已被 IIS 占用。如果两个应用程序都设计成独占使用同一端口,则一次只有其中一个应用程序能够成功运行。


临时端口

在 Microsoft Windows XP 或 Windows Server 2003 中,由 Windows 套接字分配给应用程序的临时 TCP 或 UDP 端口号的最大值是由注册表设置 MaxUserPort 控制的,该参数的默认值为 5000。临时端口从端口号 1025 开始编号。因此,默认情况下,Windows XP 或 Windows Server 2003 会为执行通配绑定的应用程序分配一个范围从 1025 到 5000 的号码。

要在运行 Windows XP 或 Windows Server 2003 的计算机上更改临时端口的最大值,请执行以下操作:

1.

单击开始,再单击运行,键入 regedit.exe,然后单击确定

2.

找到而后单击以下注册表子项:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

3.

编辑菜单上,指向新建,然后单击双字节值

4.

键入 MaxUserPort,然后按 ENTER。

5.

双击 MaxUserPort 值,然后以十进制或十六进制键入最大值。

键入的数值必须在 5000¨C65534(十进制)之间。如果此参数设置的值超出有效范围,则使用最接近的有效值(5000 或 65534)。

6.

单击确定

7.

退出注册表编辑器。

警告 如果错误使用注册表编辑器,可能会导致严重问题以至于需要您重新安装操作系统。Microsoft 无法保证您能够解决由于错误使用注册表编辑器而引起的问题。您必须自行承担使用注册表编辑器所带来的风险。

必须重新启动计算机,方可使 MaxUserPort 注册表设置更改生效。

如果应用程序使用通配绑定同时打开大量连接,可能只需更改这个值,而且需确保应用程序不会用尽可用的临时端口。例如,一个使用文件传输协议 (FTP) 传输大量小文件的数据备份应用程序就可能用尽临时端口。


端口保留

通过端口保留,应用程序可以阻止一定范围内的端口在通配绑定期间被分配。然而,保留某一端口范围并不会阻止应用程序在保留的范围内执行特定的绑定(请求使用特定端口)。保留端口范围时,所选择的端口号连续范围必须是从 1025 到 MaxUserPort 设置值(默认值为 5000)或从 49152 到 65535。多个客户端应用程序可保留相同的范围。取消保留(删除保留)时,Windows 套接字会删除它找到的第一个完全包含在取消保留请求内的条目。

还可以执行以下操作,通过注册表来指定保留端口的范围:

1.

单击开始,再单击运行,键入 regedit.exe,然后单击确定

2.

找到而后单击以下注册表子项:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

3.

编辑菜单上,指向新建,然后单击多字符串值

4.

键入 ReservedPorts,然后按 ENTER。

5.

双击 ReservedPorts 值,使用以下语法键入端口范围:x-y

要指定单个端口,请对 x 和 y 使用相同的值。例如,要指定端口 4000,请键入 4000-4000

6.

单击确定

7.

退出注册表编辑器。

端口范围

通过端口封锁,应用程序可以防止其他应用程序执行对指定范围内端口的特定绑定。封锁端口范围时,应用程序所选择的连续端口号范围必须介于 MaxUserPort 设置值(默认值为 5000)+ 1 与 49151(对于未安装服务包的 Windows XP 和 Windows Server 2003)或 65535(对于 Windows Server 2003 Service Pack 1)之间。不能存在到封锁端口范围内端口的现有绑定。Windows 套接字会以句柄形式返回封锁范围内的最后一个端口号。解除封锁(取消封锁)时,Windows 套接字会解除与解除封锁请求具有相同左边界的封锁范围。


端口范围

对于运行未安装服务包的 Windows XP 或 Windows Server 2003 的计算机,下面给出了不同的端口范围:

众所周知的端口范围(由 IANA 保留):0 到 1023

临时端口范围(对于通配绑定):1025 到 MaxUserPort 注册表设置值

可用作特定端口(对于特定绑定):从 0 到 65535 的任何未封锁端口

保留端口的可用范围:1025 到 MaxUserPort 以及 49152 到 65535

封锁端口的可用范围:MaxUserPort + 1 到 49151(除非 MaxUserPort 的值设置为 49152 或更高,这种情况下没有可封锁端口范围)

对于运行未安装服务包的 Windows XP 或 Windows Server 2003 的计算机,下图显示了不同的端口范围。

端口范围

尽管将众所周知的端口范围、可保留的端口范围以及可封锁的端口范围分开是很有意义的,但有时需要将 MaxUserPort 设置为高于 49152 的值并且需要封锁端口。为了给端口请求提供服务并保持向后兼容,Windows Server 2003 Service Pack 1 (SP1) 允许在保留范围内封锁端口。因此,对于 Windows Server 2003 SP1,范围如下所示:

众所周知的端口范围(由 IANA 保留):0 到 1023

临时端口范围:1025 到 MaxUserPort 注册表设置值

可用作特定端口:从 0 到 65535 的任何未封锁端口

保留端口的可用范围:1025 到 MaxUserPort 以及 49152 到 65535

封锁端口的可用范围:MaxUserPort + 1 到 65535

对于运行带 SP1 的 Windows Server 2003 的计算机,下图显示了不同的端口范围。

端口范围

0

Rails RESTful (1) 什麼是REST?


on Rails 1.2 的一個重要進展是 RESTful,在了解怎麼用之前,我們要先了解什麼是 REST(Representational State Transfer)?

什麼是REST?

REST 是一種分散式超媒體系統(如WWW)的軟體架構風格,你可以想像它是一個良好設計的Web應用程式規則: 一組網路Web頁面(虛擬的狀態機器),其中 Client 透過點選超連結(狀態變換),結果是下個Web頁面(表示應用程式的下一個狀態)。

REST 所描述的網路系統包括三個部份:
data elements (resource, resource identifier, representation)
connectors (client, , , resolver, tunnel)
components (origin server, gateway, proxy, user agent)

幾個重點:
Data elements 由標準化介面存取
Components 透過介面傳輸 資源表徵 (representations of resources) 來溝通,而不是直接操作資源本身。
Connectors 提供 component 的抽象介面來溝通,隱藏溝通機制的實作細節。
Components 使用 connectors 來存取,connectors 提供資源的存取或居中。
所有來自 connector 的 requests 必須包含所有必要的資訊來了解該 request,不需要依靠之前的request (即 stateless)

嚴格來說REST符合以下幾個條件:
應用程式的狀態跟功能拆成 resources
每個 resource 使用獨一無二用來當作超連結的通用定位語法(在WWW中即URI)
所有 resources 共用一致的介面在 client 跟 resource 之間轉換狀態,包括:
一組有限的良好定義操作 well-defined operations
一組有限的內容格式 content types,也許包括 可執行的程式碼 code-on-demand (在WWW中即Javascript)
這種通訊協定 protocol (在WWW中即用HTTP) 包含以下特色:
使用者端/伺服器端 Client/Server
狀態無關 Stateless
可以快取 Cacheable
分層的 Layered

符合 REST principles 的系統稱做 RESTful。

一般來說REST這個詞彙常被用來描述任何使用XML (or YAML, JSON, plain text) 的簡單介面,而不須靠其他機制(如SOAP)。另外 REST 雖然是個來自 WWW 的架構概念(比WWW晚),但是這兩者並不是綁在一起,有可能設計一個大型軟體系統符合REST但是不用HTTP協定也不需跟WWW互動,也有可能設計一個簡單的 XML+HTTP 界面使用 RPC model 而不符合 REST principles。

Resources

REST的一個最重要的觀念就是 resources (特定資訊的資源),每一個 resource 由一個 global identifier (即URI)所表示。為了操作這些 resources,網路的 components (即 clients 跟servers) 透過標準化的介面 (即HTTP) 來溝通並交換這些 resources 的 representations (即實際上傳達資訊的文件).

任意數量的 connectors (如clients, servers, caches, tunnels等) 可以居中 request,但是都不可以 “seeing past” (不需要其他 layer層)。這樣的應用程式跟一個 resource 互動根據兩件事情: resource的URI 跟 要做的動作 – 它不需要知道是否有 caches, proxies, gateways, firewalls, tunnels, 或其他任何藏在sever之間的東西。這個應用程式只需要知道資訊的格式 (representation),通常是 HTML或 XML 或圖片什麼的。

REST 有什麼優點?
支援快取 caching 將改善反應時間跟server的負載能力。
因為不必維持連結狀態,大大改善 server 的 scalability 能力。這表示不同server可以處理同一串 requests。
一個瀏覽器就可以存取任一應用程式跟資源,client 端不需使用別的軟體。
在HTTP之上不依存其他機制跟軟體。
跟其他連結方式相比(如RPC),可以提供相等的功能。
不需要其他的 discovery 機制,因為使用超連結了。
提供比RPC更好的長期相容性,因為 :
如同HTML這種文件具有後前及向後的相容能力
支援新的內容格式不需要丟掉舊的

另外比起RPC-style,URL command line 有極佳的 human-friendly 優點,容易 discovered/ transmitted /scripted/bookmarked 一個 URL。請參考 The Beauty of REST 跟 Tangled in the Threads 的優點介紹。

跟 RPC 的比較

跟 REST 應用程式對比的就是 RPC (Remote procedure call,實作上有XML-RPC或SOAP等) 了。RPC 應用程式曝露一或多個網路物件,每個有特定的 functions 可以呼叫。在 client 與物件溝通之前,它必須知道這個物件的知識來操作。

REST 的設計限制了 resource 的面向,它定義了介面 (動詞 verbs 跟內容型別 content types),導致比RPC更少的型別,但是更多的resource identifiers (名詞nouns)。REST 的設計尋求定義一組 resources 讓 Clients 可以一致性的互動,而且提供超連結在資源之間可以瀏覽,而不需要了解整個 resources 的知識 。Server 提供的表單 forms 也可以被用在 RESTful 的環境來描述 clients 如何建構 URL 來跟特定的resource做溝通。

這張圖指出了REST的三位一體 : Nouns, 有限的 Verbs 跟 Content Types。

需注意的是,根據不同的用法要求跟效率,在不同的應用程式環境中,該使用哪種架構仍有很大討論的空間跟爭議(SOAP的支持者認為REST仍有其侷限,只適合簡單的應用)。REST的重要性在於它有個目前最成功的大型軟體架構應用: Wide World Web。RESTful 是 Web 的天性,也是讓 Web 成功的原因,因此 RESTful 的支持者認為使用 RESTful 架構就是 Web上最好的方法來做到有擴充性(scalable),彈性跟有威力的應用程式。在有這麼多複雜的RPC技術之後,REST因其簡單又有威力的架構近來越來越受到矚目跟重視。

舉例

一個 RPC 應用程式可能會定義以下的操作:

getUser()
addUser()
removeUser()
updateUser()
getLocation()
addLocation()
removeLocation()
updateLocation()
listUsers()
listLocations()
findLocation()
findUser()

Client 的程式碼可能會這樣存取:

exampleAppObject = new ExampleApp(”example.com:1234″)
exampleAppObject.getUser()

在 REST中,重點在 resources(或稱作 nouns)的多樣性,比如說可能有以下的用法:

http://example.com/users/
http://example.com/users/{user} (one for each user)
http://example.com/findUserForm
http://example.com/locations/
http://example.com/locations/{location} (one for each location)
http://example.com/findLocationForm

Client 的程式碼可能這樣存取:

userResource = new Resource(http://example.com/users/001)
userResource.get()

每個 resource 擁有自己的識別名詞,而 Clients 從單一 resource 開始瀏覽,透過標準操作走訪 resource ,如 GET 下載,PUT更新,DELETE刪除,POST新增,注意到每個物件有自己的URL,而且可以容易被快取,複製跟書籤化(bookmarked)。

參考資源
Representational State Transfer
RestWiki
How to Create a REST Protocol

From :http://ihower.idv.tw//archives/1542

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