您正在查看: 2017年2月

如何让控制台字符编码在UTF8与GBK之间切换

切换到utf-8编码,使用CHCP 65001命令,之后修改窗口属性->字体,改为lucida console字体

切换到cp936编码使用CHCP 936命令

c++ 字符类型总结区别wchar_t,char,WCHAR及转换

1.区别wchar_t,char,WCHAR

ANSI:即 char,可用字符串处理函数:strcat( ),strcpy( ), strlen( )等以str打头的函数。
UNICODE:wchar_t是Unicode字符的数据类型,它实际定义在里:
typedef unsigned short wchar_t;
另外,在头文件中有这样的定义:typedef wchar_t WCHAR; 所以WCHAR实际就是wchar_t
wchar_t 可用字符串处理函数:wcscat(),wcscpy(),wcslen()等以wcs打头的函数。为了让编译器识别Unicode字符串,必须以在前面加一个“L”,例如: wchar_t *szTest=L"This is a Unicode string.";

2.TCHAR

c语言里面提供了 _UNICODE宏(有下划线),在Windows里面提供了UNICODE宏(无下划线),只要定了_UNICODE宏和UNICODE宏,系统就会自 动切换到UNICODE版本,否则,系统按照ANSI的方式进行编译和运行。只定义了宏并不能实现自动的转换,他还需要一系列的字符定义支持。
1. TCHAR
如果定义了UNICODE宏则TCHAR被定义为wchar_t。
typedef wchar_t TCHAR;
否则TCHAR被定义为char typedef char TCHAR;
2. LPTSTR
如果定义了UNICODE宏则LPTSTR被定义为LPWSTR。
typedef LPTSTR LPWSTR;
否则TCHAR被定义为char typedef LPTSTR LPSTR;
说明:在使用字符串常量的时候需要使用_TEXT(“MyStr”)或者_T("")来支持系统的自动转换。

3.BSTR

BSTR是一个带长度前缀的字符串,主要由操作系统来管理的,所以要用api.主要用来和VB打交道的(VB里的string就是指它)要操作它的API函数有很多.比如SysAllocString,SysFreeString等等.
vc里封装它的类如_bstr_t,及ATL中的CComBSTR等.
一个 BSTR 由头部和字符串组成,头部包含了字符串的长度信息,字符串中可以包含嵌入的 null 值。
BSTR 是以指针的形式进行传递的。(指针是一个变量,包含另外一个变量的内存地址,而不是数据。) BSTR 是 Unicode 的,即每个字符需要两个字节。 BSTR 通常以两字节的 null 字符结束。 wstr是宽字符,以双字节表示一个字符 bstr是为了与原先的basic字符兼容,它的最前面的4个字节为其长度,以'\0'结束.

4.更进一步的字符串以及其指针的类型定义 

由于win32 API文档的函数列表使用函数的常用名字(例如, "SetWindowText"),所有的字符串都是用TCHAR来定义的。(除了XP中引入的只适用于Unicode的API)。下面列出一些常用的typedefs,你可以在msdn中看到他们。

type Meaning in MBCS builds Meaning in Unicode builds
WCHAR wchar_t wchar_t
LPSTR char* char* LPCSTR const char* const char* LPWSTR wchar_t* wchar_t* LPCWSTR wchar_t* wchar_t* TCHAR TCHAR char wchar_t
LPTSTR TCHAR* TCHAR* LPCTSTR const TCHAR* const TCHAR*

5.相互转换

(1) char转换成CString
  若将char
转换成CString,除了直接赋值外,还可使用CString::Format进行。例如:
char chArray[] = "This is a test";
char * p = "This is a test";
  或
LPSTR p = "This is a test";
  或在已定义Unicode应的用程序中
TCHAR * p = _T("This is a test");
  或
LPTSTR p = _T("This is a test");
CString theString = chArray;
theString.Format(_T("%s"), chArray);
theString = p;
  (2) CString转换成char*   若将CString类转换成char*(LPSTR)类型,常常使用下列三种方法:
  方法一,使用强制转换。例如:
CString theString( "This is a test" );
LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;
  方法二,使用strcpy。例如:
CString theString( "This is a test" );
LPTSTR lpsz = new TCHAR[theString.GetLength()+1];
_tcscpy(lpsz, theString);
  需要说明的是,strcpy(或可移值Unicode/MBCS的_tcscpy)的第二个参数是 const wchar_t* (Unicode)或const char* (ANSI),系统编译器将会自动对其进行转换。
  方法三,使用CString::GetBuffer。例如:
CString s(_T("This is a test "));
LPTSTR p = s.GetBuffer();
// 在这里添加使用p的代码
if(p != NULL) *p = _T('\0');
s.ReleaseBuffer();
// 使用完后及时释放,以便能使用其它的CString成员函数
  (3) BSTR转换成char*   方法一,使用ConvertBSTRToString。例如:
#include
#pragma comment(lib, "comsupp.lib")
int _tmain(int argc, _TCHAR* argv[]){
BSTR bstrText = ::SysAllocString(L"Test");
char* lpszText2 = _com_util::ConvertBSTRToString(bstrText);
SysFreeString(bstrText); // 用完释放
delete[] lpszText2;
return 0;
}
  方法二,使用_bstr_t的赋值运算符重载。例如:
需要引用头文件#include <comdef.h>
_bstr_t b = bstrText;
char* lpszText2 = b;
  (4) char*转换成BSTR
  方法一,使用SysAllocString等API函数。例如:
BSTR bstrText = ::SysAllocString(L"Test");
BSTR bstrText = ::SysAllocStringLen(L"Test",4);
BSTR bstrText = ::SysAllocStringByteLen("Test",4);
  方法二,使用COleVariant或_variant_t。例如:
//COleVariant strVar("This is a test");
_variant_t strVar("This is a test");
BSTR bstrText = strVar.bstrVal;
  方法三,使用_bstr_t,这是一种最简单的方法。例如:
BSTR bstrText = _bstr_t("This is a test");
  方法四,使用CComBSTR。例如:
BSTR bstrText = CComBSTR("This is a test");
  或
CComBSTR bstr("This is a test");
BSTR bstrText = bstr.m_str;
  方法五,使用ConvertStringToBSTR。例如:
char* lpszText = "Test";
BSTR bstrText = _com_util::ConvertStringToBSTR(lpszText);
  (5) CString转换成BSTR
  通常是通过使用CStringT::AllocSysString来实现。例如:
CString str("This is a test");
BSTR bstrText = str.AllocSysString();

SysFreeString(bstrText); // 用完释放
  (6) BSTR转换成CString
  一般可按下列方法进行:
BSTR bstrText = ::SysAllocString(L"Test");
CStringA str;
str.Empty();
str = bstrText;
  或
CStringA str(bstrText);
  (7) ANSI、Unicode和宽字符之间的转换
  方法一,使用MultiByteToWideChar将ANSI字符转换成Unicode字符,使用WideCharToMultiByte将Unicode字符转换成ANSI字符。
  方法二,使用“_T”将ANSI转换成“一般”类型字符串,使用“L”将ANSI转换成Unicode,而在托管C++环境中还可使用S将ANSI字符串转换成String*对象。例如:
TCHAR tstr[] = _T("this is a test");
wchar_t wszStr[] = L"This is a test";
String* str = S”This is a test”;
  方法三,使用ATL 7.0的转换宏和类。ATL7.0在原有3.0基础上完善和增加了许多字符串转换宏以及提供相应的类,它具有如图3所示的统一形式:
  其中,第一个C表示“类”,以便于ATL 3.0宏相区别,第二个C表示常量,2表示“to”,EX表示要开辟一定大小的缓冲。SourceType和DestinationType可以是A、 T、W和OLE,其含义分别是ANSI、Unicode、“一般”类型和OLE字符串。例如,CA2CT就是将ANSI转换成一般类型的字符串常量。下面 是一些示例代码:
LPTSTR tstr= CA2TEX<16>("this is a test");
LPCTSTR tcstr= CA2CT("this is a test");
wchar_t wszStr[] = L"This is a test";
char* chstr = CW2A(wszStr);

Duilib中Webbrowser事件完善使其支持判断页面加载完毕

在多iframe的页面中,需要结合DISPID_DOCUMENTCOMPLETE和DISPID_NAVIGATECOMPLETE2两个事件判断页面是否加载完毕,而duilib中没有提供对DISPID_DOCUMENTCOMPLETE的支持。

要支持DISPID_DOCUMENTCOMPLETE,需要修改UIWebBrowser.cpp、UIWebBrowser.h和WebBrowserEventHandler.h三个文件

1.WebBrowserEventHandler.h文件

添加virtual void DocumentComplete();

#pragma once
#include <ExDisp.h>
#include <ExDispid.h>
#include <mshtmhst.h>

namespace DuiLib
{
    class CWebBrowserEventHandler
    {
    public:
        CWebBrowserEventHandler() {}
        ~CWebBrowserEventHandler() {}

        virtual void BeforeNavigate2( IDispatch *pDisp,VARIANT *&url,VARIANT *&Flags,VARIANT *&TargetFrameName,VARIANT *&PostData,VARIANT *&Headers,VARIANT_BOOL *&Cancel ) {}
        virtual void NavigateError(IDispatch *pDisp,VARIANT * &url,VARIANT *&TargetFrameName,VARIANT *&StatusCode,VARIANT_BOOL *&Cancel) {}
        virtual void NavigateComplete2(IDispatch *pDisp,VARIANT *&url){}
        virtual void DocumentComplete(){} //2016.10.19
        virtual void ProgressChange(LONG nProgress, LONG nProgressMax){}
        virtual void NewWindow3(IDispatch **pDisp, VARIANT_BOOL *&Cancel, DWORD dwFlags, BSTR bstrUrlContext, BSTR bstrUrl){}
        virtual void CommandStateChange(long Command,VARIANT_BOOL Enable){};

        // interface IDocHostUIHandler
        virtual HRESULT STDMETHODCALLTYPE ShowContextMenu(
            /* [in] */ DWORD dwID,
            /* [in] */ POINT __RPC_FAR *ppt,
            /* [in] */ IUnknown __RPC_FAR *pcmdtReserved,
            /* [in] */ IDispatch __RPC_FAR *pdispReserved)
        {
            //return E_NOTIMPL;
            //返回 E_NOTIMPL 正常弹出系统右键菜单
            return S_OK;
            //返回S_OK 则可屏蔽系统右键菜单
        }

        virtual HRESULT STDMETHODCALLTYPE GetHostInfo(
            /* [out][in] */ DOCHOSTUIINFO __RPC_FAR *pInfo)
        {
            //         if (pInfo != NULL)
            //         {
            //             pInfo->dwFlags |= DOCHOSTUIFLAG_NO3DBORDER;
            //         }
            return S_OK;
        }

        virtual HRESULT STDMETHODCALLTYPE ShowUI(
            /* [in] */ DWORD dwID,
            /* [in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject,
            /* [in] */ IOleCommandTarget __RPC_FAR *pCommandTarget,
            /* [in] */ IOleInPlaceFrame __RPC_FAR *pFrame,
            /* [in] */ IOleInPlaceUIWindow __RPC_FAR *pDoc)
        {
            return S_FALSE;
        }

        virtual HRESULT STDMETHODCALLTYPE HideUI( void)
        {
            return S_OK;
        }

        virtual HRESULT STDMETHODCALLTYPE UpdateUI( void)
        {
            return S_OK;
        }

        virtual HRESULT STDMETHODCALLTYPE EnableModeless(
            /* [in] */ BOOL fEnable)
        {
            return S_OK;
        }

        virtual HRESULT STDMETHODCALLTYPE OnDocWindowActivate(
            /* [in] */ BOOL fActivate)
        {
            return S_OK;
        }

        virtual HRESULT STDMETHODCALLTYPE OnFrameWindowActivate(
            /* [in] */ BOOL fActivate)
        {
            return S_OK;
        }

        virtual HRESULT STDMETHODCALLTYPE ResizeBorder(
            /* [in] */ LPCRECT prcBorder,
            /* [in] */ IOleInPlaceUIWindow __RPC_FAR *pUIWindow,
            /* [in] */ BOOL fRameWindow)
        {
            return S_OK;
        }

        virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(
            /* [in] */ LPMSG lpMsg,
            /* [in] */ const GUID __RPC_FAR *pguidCmdGroup,
            /* [in] */ DWORD nCmdID)
        {
            return S_FALSE;
        }

        virtual HRESULT STDMETHODCALLTYPE GetOptionKeyPath(
            /* [out] */ LPOLESTR __RPC_FAR *pchKey,
            /* [in] */ DWORD dw)
        {
            return S_OK;
        }

        virtual HRESULT STDMETHODCALLTYPE GetDropTarget(
            /* [in] */ IDropTarget __RPC_FAR *pDropTarget,
            /* [out] */ IDropTarget __RPC_FAR *__RPC_FAR *ppDropTarget)
        {
            return E_NOTIMPL;
        }

        virtual HRESULT STDMETHODCALLTYPE GetExternal(
            /* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDispatch)
        {
            return E_NOTIMPL;
        }

        virtual HRESULT STDMETHODCALLTYPE TranslateUrl(
            /* [in] */ DWORD dwTranslate,
            /* [in] */ OLECHAR __RPC_FAR *pchURLIn,
            /* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppchURLOut)
        {
            return S_OK;
        }

        virtual HRESULT STDMETHODCALLTYPE FilterDataObject(
            /* [in] */ IDataObject __RPC_FAR *pDO,
            /* [out] */ IDataObject __RPC_FAR *__RPC_FAR *ppDORet)
        {
            return S_OK;
        }

        //     virtual HRESULT STDMETHODCALLTYPE GetOverrideKeyPath( 
        //         /* [annotation][out] */ 
        //         __deref_out  LPOLESTR *pchKey,
        //         /* [in] */ DWORD dw)
        //     {
        //         return E_NOTIMPL;
        //     }

        // IDownloadManager
        virtual HRESULT STDMETHODCALLTYPE Download( 
            /* [in] */ IMoniker *pmk,
            /* [in] */ IBindCtx *pbc,
            /* [in] */ DWORD dwBindVerb,
            /* [in] */ LONG grfBINDF,
            /* [in] */ BINDINFO *pBindInfo,
            /* [in] */ LPCOLESTR pszHeaders,
            /* [in] */ LPCOLESTR pszRedir,
            /* [in] */ UINT uiCP)
        {
            return S_OK;
        }
    };
}

2.在UIWebBrowser.h添加

void DocumentComplete();

#ifndef __UIWEBBROWSER_H__
#define __UIWEBBROWSER_H__

#pragma once

#include "../Utils/WebBrowserEventHandler.h"
#include <ExDisp.h>

namespace DuiLib
{
    class UILIB_API CWebBrowserUI
        : public CActiveXUI
        , public IDocHostUIHandler
        , public IServiceProvider
        , public IOleCommandTarget
        , public IDispatch
        , public ITranslateAccelerator
    {
    public:
        /// 构造函数
        CWebBrowserUI();
        virtual ~CWebBrowserUI();

        void SetHomePage(LPCTSTR lpszUrl);
        LPCTSTR GetHomePage();

        void SetAutoNavigation(bool bAuto = TRUE);
        bool IsAutoNavigation();

        void SetWebBrowserEventHandler(CWebBrowserEventHandler* pEventHandler);
        void Navigate2(LPCTSTR lpszUrl);
        void Refresh();
        void Refresh2(int Level);
        void GoBack();
        void GoForward();
        void NavigateHomePage();
        void NavigateUrl(LPCTSTR lpszUrl);
        virtual bool DoCreateControl();
        IWebBrowser2* GetWebBrowser2(void);
        IDispatch*           GethtmlWindow();
        static DISPID FindId(IDispatch *pObj, LPOLESTR pName);
        static HRESULT InvokeMethod(IDispatch *pObj, LPOLESTR pMehtod, VARIANT *pVarResult, VARIANT *ps, int cArgs);
        static HRESULT GetProperty(IDispatch *pObj, LPOLESTR pName, VARIANT *pValue);
        static HRESULT SetProperty(IDispatch *pObj, LPOLESTR pName, VARIANT *pValue);

    protected:
        IWebBrowser2*            m_pWebBrowser2; //浏览器指针
        IhtmlWindow2*        _pHtmlWnd2;
        LONG m_dwRef;
        DWORD m_dwCookie;
        virtual void ReleaseControl();
        HRESULT RegisterEventHandler(BOOL inAdvise);
        virtual void SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue);
        CDuiString m_sHomePage;    // 默认页面
        bool m_bAutoNavi;    // 是否启动时打开默认页面
        CWebBrowserEventHandler* m_pWebBrowserEventHandler;    //浏览器事件处理

        // DWebBrowserEvents2
        void BeforeNavigate2( IDispatch *pDisp,VARIANT *&url,VARIANT *&Flags,VARIANT *&TargetFrameName,VARIANT *&PostData,VARIANT *&Headers,VARIANT_BOOL *&Cancel );
        void NavigateError(IDispatch *pDisp,VARIANT * &url,VARIANT *&TargetFrameName,VARIANT *&StatusCode,VARIANT_BOOL *&Cancel);
        void NavigateComplete2(IDispatch *pDisp,VARIANT *&url);
        void ProgressChange(LONG nProgress, LONG nProgressMax);
        void NewWindow3(IDispatch **pDisp, VARIANT_BOOL *&Cancel, DWORD dwFlags, BSTR bstrUrlContext, BSTR bstrUrl);
        void CommandStateChange(long Command,VARIANT_BOOL Enable);
        void DocumentComplete();//201610.19
    public:
        virtual LPCTSTR GetClass() const;
        virtual LPVOID GetInterface( LPCTSTR pstrName );

        // IUnknown
        STDMETHOD_(ULONG,AddRef)();
        STDMETHOD_(ULONG,Release)();
        STDMETHOD(QueryInterface)(REFIID riid, LPVOID *ppvObject);

        // IDispatch
        virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount( __RPC__out UINT *pctinfo );
        virtual HRESULT STDMETHODCALLTYPE GetTypeInfo( UINT iTInfo, LCID lcid, __RPC__deref_out_opt ITypeInfo **ppTInfo );
        virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames( __RPC__in REFIID riid, __RPC__in_ecount_full(cNames ) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __RPC__out_ecount_full(cNames) DISPID *rgDispId);
        virtual HRESULT STDMETHODCALLTYPE Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr );

        // IDocHostUIHandler
        STDMETHOD(ShowContextMenu)(DWORD dwID, POINT* pptPosition, IUnknown* pCommandTarget, IDispatch* pDispatchObjectHit);
        STDMETHOD(GetHostInfo)(DOCHOSTUIINFO* pInfo);
        STDMETHOD(ShowUI)(DWORD dwID, IOleInPlaceActiveObject* pActiveObject, IOleCommandTarget* pCommandTarget, IOleInPlaceFrame* pFrame, IOleInPlaceUIWindow* pDoc);
        STDMETHOD(HideUI)();
        STDMETHOD(UpdateUI)();
        STDMETHOD(EnableModeless)(BOOL fEnable);
        STDMETHOD(OnDocWindowActivate)(BOOL fActivate);
        STDMETHOD(OnFrameWindowActivate)(BOOL fActivate);
        STDMETHOD(ResizeBorder)(LPCRECT prcBorder, IOleInPlaceUIWindow* pUIWindow, BOOL fFrameWindow);
        STDMETHOD(TranslateAccelerator)(LPMSG lpMsg, const GUID* pguidCmdGroup, DWORD nCmdID);    //浏览器消息过滤
        STDMETHOD(GetOptionKeyPath)(LPOLESTR* pchKey, DWORD dwReserved);
        STDMETHOD(GetDropTarget)(IDropTarget* pDropTarget, IDropTarget** ppDropTarget);
        STDMETHOD(GetExternal)(IDispatch** ppDispatch);
        STDMETHOD(TranslateUrl)(DWORD dwTranslate, OLECHAR* pchURLIn, OLECHAR** ppchURLOut);
        STDMETHOD(FilterDataObject)(IDataObject* pDO, IDataObject** ppDORet);

        // IServiceProvider
        STDMETHOD(QueryService)(REFGUID guidService, REFIID riid, void** ppvObject);

        // IOleCommandTarget
        virtual HRESULT STDMETHODCALLTYPE QueryStatus( __RPC__in_opt const GUID *pguidCmdGroup, ULONG cCmds, __RPC__inout_ecount_full(cCmds ) OLECMD prgCmds[ ], __RPC__inout_opt OLECMDTEXT *pCmdText);
        virtual HRESULT STDMETHODCALLTYPE Exec( __RPC__in_opt const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, __RPC__in_opt VARIANT *pvaIn, __RPC__inout_opt VARIANT *pvaOut );

        // IDownloadManager
        STDMETHOD(Download)( 
            /* [in] */ IMoniker *pmk,
            /* [in] */ IBindCtx *pbc,
            /* [in] */ DWORD dwBindVerb,
            /* [in] */ LONG grfBINDF,
            /* [in] */ BINDINFO *pBindInfo,
            /* [in] */ LPCOLESTR pszHeaders,
            /* [in] */ LPCOLESTR pszRedir,
            /* [in] */ UINT uiCP);

        // ITranslateAccelerator
        // Duilib消息分发给WebBrowser
        virtual LRESULT TranslateAccelerator( MSG *pMsg );
    };
} // namespace DuiLib
#endif // __UIWEBBROWSER_H__

3.UIWebBrowser.cpp添加实现

#include "StdAfx.h"
#include "UIWebBrowser.h"
#include <atlconv.h>
#include <atlcomcli.h>
#include "../Utils/downloadmgr.h"
#include <mshtml.h>

DuiLib::CWebBrowserUI::CWebBrowserUI()
: m_pWebBrowser2(NULL)
, _pHtmlWnd2(NULL)
, m_pWebBrowserEventHandler(NULL)
, m_bAutoNavi(false)
, m_dwRef(0)
, m_dwCookie(0)
{
    m_clsid=CLSID_WebBrowser;
    m_sHomePage.Empty();
}

bool DuiLib::CWebBrowserUI::DoCreateControl()
{
    if (!CActiveXUI::DoCreateControl())
        return false;
    GetManager()->AddTranslateAccelerator(this);
    GetControl(IID_IWebBrowser2,(LPVOID*)&m_pWebBrowser2);
    if ( m_bAutoNavi && !m_sHomePage.IsEmpty())
    {
        this->Navigate2(m_sHomePage);
    }
    RegisterEventHandler(TRUE);
    return true;
}

void DuiLib::CWebBrowserUI::ReleaseControl()
{
    m_bCreated=false;
    GetManager()->RemoveTranslateAccelerator(this);
    RegisterEventHandler(FALSE);
}

DuiLib::CWebBrowserUI::~CWebBrowserUI()
{
    ReleaseControl();
}

STDMETHODIMP DuiLib::CWebBrowserUI::GetTypeInfoCount( UINT *iTInfo )
{
    *iTInfo = 0;
    return E_NOTIMPL;
}

STDMETHODIMP DuiLib::CWebBrowserUI::GetTypeInfo( UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo )
{
    return E_NOTIMPL;
}

STDMETHODIMP DuiLib::CWebBrowserUI::GetIDsOfNames( REFIID riid, OLECHAR **rgszNames, UINT cNames, LCID lcid,DISPID *rgDispId )
{
    return E_NOTIMPL;
}

STDMETHODIMP DuiLib::CWebBrowserUI::Invoke( DISPID dispIdMember, REFIID riid, LCID lcid,WORD wFlags, DISPPARAMS* pDispParams,VARIANT* pVarResult, EXCEPINFO* pExcepInfo,UINT* puArgErr )
{
    if ((riid != IID_NULL))
        return E_INVALIDARG;

    switch(dispIdMember)
    {
    case DISPID_BEFORENAVIGATE2:
        BeforeNavigate2(
            pDispParams->rgvarg[6].pdispVal,
            pDispParams->rgvarg[5].pvarVal,
            pDispParams->rgvarg[4].pvarVal,
            pDispParams->rgvarg[3].pvarVal,
            pDispParams->rgvarg[2].pvarVal,
            pDispParams->rgvarg[1].pvarVal,
            pDispParams->rgvarg[0].pboolVal);
        break;
    case DISPID_COMMANDSTATECHANGE:
        CommandStateChange(
            pDispParams->rgvarg[1].lVal,
            pDispParams->rgvarg[0].boolVal);
        break;
    case DISPID_NAVIGATECOMPLETE2:
        NavigateComplete2(
            pDispParams->rgvarg[1].pdispVal,
            pDispParams->rgvarg[0].pvarVal);
        break;
    case DISPID_NAVIGATEERROR:
        NavigateError(
            pDispParams->rgvarg[4].pdispVal,
            pDispParams->rgvarg[3].pvarVal,
            pDispParams->rgvarg[2].pvarVal,
            pDispParams->rgvarg[1].pvarVal,
            pDispParams->rgvarg[0].pboolVal);
        break;
    case DISPID_STATUSTEXTCHANGE:
        break;
        //      case DISPID_NEWWINDOW2:
        //          break;
    case DISPID_NEWWINDOW3:
        NewWindow3(
            pDispParams->rgvarg[4].ppdispVal,
            pDispParams->rgvarg[3].pboolVal,
            pDispParams->rgvarg[2].uintVal,
            pDispParams->rgvarg[1].bstrVal,
            pDispParams->rgvarg[0].bstrVal);
        break;
//     case DISPID_PROPERTYCHANGE:
//         if (pDispParams->cArgs>0 && pDispParams->rgvarg[0].vt == VT_BSTR) {
//             TRACE(_T("PropertyChange(%s)\n"), pDispParams->rgvarg[0].bstrVal);
//         }
//         break;

    case DISPID_DOCUMENTCOMPLETE:
        DocumentComplete();//2016.10.19
        break;
    default:
        return DISP_E_MEMBERNOTFOUND;
    }
    return S_OK;
}

STDMETHODIMP DuiLib::CWebBrowserUI::QueryInterface( REFIID riid, LPVOID *ppvObject )
{
    *ppvObject = NULL;

    if( riid == IID_IDocHostUIHandler)
        *ppvObject = static_cast<IDocHostUIHandler*>(this);
    else if( riid == IID_IDispatch)
        *ppvObject = static_cast<IDispatch*>(this);
    else if( riid == IID_IServiceProvider)
        *ppvObject = static_cast<IServiceProvider*>(this);
    else if (riid == IID_IOleCommandTarget)
        *ppvObject = static_cast<IOleCommandTarget*>(this);

    if( *ppvObject != NULL )
        AddRef();
    return *ppvObject == NULL ? E_NOINTERFACE : S_OK;
}

STDMETHODIMP_(ULONG) DuiLib::CWebBrowserUI::AddRef()
{
    InterlockedIncrement(&m_dwRef); 
    return m_dwRef;
}

STDMETHODIMP_(ULONG) DuiLib::CWebBrowserUI::Release()
{
    ULONG ulRefCount = InterlockedDecrement(&m_dwRef);
    return ulRefCount; 
}

void DuiLib::CWebBrowserUI::Navigate2( LPCTSTR lpszUrl )
{
    if (lpszUrl == NULL)
        return;

    if (m_pWebBrowser2)
    {
        CVariant url;
        url.vt=VT_BSTR;
        url.bstrVal=T2BSTR(lpszUrl);
        HRESULT hr = m_pWebBrowser2->Navigate2(&url, NULL, NULL, NULL, NULL);
    }
}

void DuiLib::CWebBrowserUI::Refresh()
{
    if (m_pWebBrowser2)
    {
        m_pWebBrowser2->Refresh();
    }
}
void DuiLib::CWebBrowserUI::GoBack()
{
    if (m_pWebBrowser2)
    {
        m_pWebBrowser2->GoBack();
    }
}
void DuiLib::CWebBrowserUI::GoForward()
{
    if (m_pWebBrowser2)
    {
        m_pWebBrowser2->GoForward();
    }
}
/// DWebBrowserEvents2
void DuiLib::CWebBrowserUI::BeforeNavigate2( IDispatch *pDisp,VARIANT *&url,VARIANT *&Flags,VARIANT *&TargetFrameName,VARIANT *&PostData,VARIANT *&Headers,VARIANT_BOOL *&Cancel )
{
    if (m_pWebBrowserEventHandler)
    {
        m_pWebBrowserEventHandler->BeforeNavigate2(pDisp,url,Flags,TargetFrameName,PostData,Headers,Cancel);
    }
}

void DuiLib::CWebBrowserUI::NavigateError( IDispatch *pDisp,VARIANT * &url,VARIANT *&TargetFrameName,VARIANT *&StatusCode,VARIANT_BOOL *&Cancel )
{
    if (m_pWebBrowserEventHandler)
    {
        m_pWebBrowserEventHandler->NavigateError(pDisp,url,TargetFrameName,StatusCode,Cancel);
    }
}

void DuiLib::CWebBrowserUI::NavigateComplete2( IDispatch *pDisp,VARIANT *&url )
{
    CComPtr<IDispatch> spDoc;   
    m_pWebBrowser2->get_Document(&spDoc);   

    if (spDoc)
    {   
        CComQIPtr<ICustomDoc, &IID_ICustomDoc> spCustomDoc(spDoc);   
        if (spCustomDoc)   
            spCustomDoc->SetUIHandler(this);   
    }

    if (m_pWebBrowserEventHandler)
    {
        m_pWebBrowserEventHandler->NavigateComplete2(pDisp,url);
    }
}

void DuiLib::CWebBrowserUI::ProgressChange( LONG nProgress, LONG nProgressMax )
{
    if (m_pWebBrowserEventHandler)
    {
        m_pWebBrowserEventHandler->ProgressChange(nProgress,nProgressMax);
    }
}

void DuiLib::CWebBrowserUI::NewWindow3( IDispatch **pDisp, VARIANT_BOOL *&Cancel, DWORD dwFlags, BSTR bstrUrlContext, BSTR bstrUrl )
{
    if (m_pWebBrowserEventHandler)
    {
        m_pWebBrowserEventHandler->NewWindow3(pDisp,Cancel,dwFlags,bstrUrlContext,bstrUrl);
    }
}
void DuiLib::CWebBrowserUI::CommandStateChange(long Command,VARIANT_BOOL Enable)
{
    if (m_pWebBrowserEventHandler)
    {
        m_pWebBrowserEventHandler->CommandStateChange(Command,Enable);
    }
}
void DuiLib::CWebBrowserUI::DocumentComplete()//2016.10.19
{
    if (m_pWebBrowserEventHandler)
    {
        m_pWebBrowserEventHandler->DocumentComplete();
    }
}

// IDownloadManager
STDMETHODIMP DuiLib::CWebBrowserUI::Download( /* [in] */ IMoniker *pmk, /* [in] */ IBindCtx *pbc, /* [in] */ DWORD dwBindVerb, /* [in] */ LONG grfBINDF, /* [in] */ BINDINFO *pBindInfo, /* [in] */ LPCOLESTR pszHeaders, /* [in] */ LPCOLESTR pszRedir, /* [in] */ UINT uiCP )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->Download(pmk,pbc,dwBindVerb,grfBINDF,pBindInfo,pszHeaders,pszRedir,uiCP);
    }
    return S_OK;
}

// IDocHostUIHandler
STDMETHODIMP DuiLib::CWebBrowserUI::ShowContextMenu( DWORD dwID, POINT* pptPosition, IUnknown* pCommandTarget, IDispatch* pDispatchObjectHit )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->ShowContextMenu(dwID,pptPosition,pCommandTarget,pDispatchObjectHit);
    }
    return S_FALSE;
}

STDMETHODIMP DuiLib::CWebBrowserUI::GetHostInfo( DOCHOSTUIINFO* pInfo )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->GetHostInfo(pInfo);
    }
    return E_NOTIMPL;
}

STDMETHODIMP DuiLib::CWebBrowserUI::ShowUI( DWORD dwID, IOleInPlaceActiveObject* pActiveObject, IOleCommandTarget* pCommandTarget, IOleInPlaceFrame* pFrame, IOleInPlaceUIWindow* pDoc )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->ShowUI(dwID,pActiveObject,pCommandTarget,pFrame,pDoc);
    }
    return S_OK;
}

STDMETHODIMP DuiLib::CWebBrowserUI::HideUI()
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->HideUI();
    }
    return S_OK;
}

STDMETHODIMP DuiLib::CWebBrowserUI::UpdateUI()
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->UpdateUI();
    }
    return S_OK;
}

STDMETHODIMP DuiLib::CWebBrowserUI::EnableModeless( BOOL fEnable )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->EnableModeless(fEnable);
    }
    return E_NOTIMPL;
}

STDMETHODIMP DuiLib::CWebBrowserUI::OnDocWindowActivate( BOOL fActivate )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->OnDocWindowActivate(fActivate);
    }
    return E_NOTIMPL;
}

STDMETHODIMP DuiLib::CWebBrowserUI::OnFrameWindowActivate( BOOL fActivate )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->OnFrameWindowActivate(fActivate);
    }
    return E_NOTIMPL;
}

STDMETHODIMP DuiLib::CWebBrowserUI::ResizeBorder( LPCRECT prcBorder, IOleInPlaceUIWindow* pUIWindow, BOOL fFrameWindow )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->ResizeBorder(prcBorder,pUIWindow,fFrameWindow);
    }
    return E_NOTIMPL;
}

STDMETHODIMP DuiLib::CWebBrowserUI::TranslateAccelerator( LPMSG lpMsg, const GUID* pguidCmdGroup, DWORD nCmdID )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->TranslateAccelerator(lpMsg,pguidCmdGroup,nCmdID);
    }
    return S_FALSE;
}

LRESULT DuiLib::CWebBrowserUI::TranslateAccelerator( MSG *pMsg )
{
    if(pMsg->message < WM_KEYFIRST || pMsg->message > WM_KEYLAST)
        return S_FALSE;

    if( m_pWebBrowser2 == NULL )
        return E_NOTIMPL;

    // 当前Web窗口不是焦点,不处理加速键
    BOOL bIsChild = FALSE;
    HWND hTempWnd = NULL;
    HWND hWndFocus = ::GetFocus();

    hTempWnd = hWndFocus;
    while(hTempWnd != NULL)
    {
        if(hTempWnd == m_hwndHost)
        {
            bIsChild = TRUE;
            break;
        }
        hTempWnd = ::GetParent(hTempWnd);
    }
    if(!bIsChild)
        return S_FALSE;

    IOleInPlaceActiveObject *pObj;
    if (FAILED(m_pWebBrowser2->QueryInterface(IID_IOleInPlaceActiveObject, (LPVOID *)&pObj)))
        return S_FALSE;

    HRESULT hResult = pObj->TranslateAccelerator(pMsg);
    pObj->Release();
    return hResult;
}

STDMETHODIMP DuiLib::CWebBrowserUI::GetOptionKeyPath( LPOLESTR* pchKey, DWORD dwReserved )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->GetOptionKeyPath(pchKey,dwReserved);
    }
    return E_NOTIMPL;
}

STDMETHODIMP DuiLib::CWebBrowserUI::GetDropTarget( IDropTarget* pDropTarget, IDropTarget** ppDropTarget )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->GetDropTarget(pDropTarget,ppDropTarget);
    }
    return S_FALSE;    // 使用系统拖拽
}

STDMETHODIMP DuiLib::CWebBrowserUI::GetExternal( IDispatch** ppDispatch )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->GetExternal(ppDispatch);
    }
    return S_FALSE;
}

STDMETHODIMP DuiLib::CWebBrowserUI::TranslateUrl( DWORD dwTranslate, OLECHAR* pchURLIn, OLECHAR** ppchURLOut )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->TranslateUrl(dwTranslate,pchURLIn,ppchURLOut);
    }
    else
    {
        *ppchURLOut = 0;
        return E_NOTIMPL;
    }
}

STDMETHODIMP DuiLib::CWebBrowserUI::FilterDataObject( IDataObject* pDO, IDataObject** ppDORet )
{
    if (m_pWebBrowserEventHandler)
    {
        return m_pWebBrowserEventHandler->FilterDataObject(pDO,ppDORet);
    }
    else
    {
        *ppDORet = 0;
        return E_NOTIMPL;
    }
}

void DuiLib::CWebBrowserUI::SetWebBrowserEventHandler( CWebBrowserEventHandler* pEventHandler )
{
    if ( pEventHandler!=NULL && m_pWebBrowserEventHandler!=pEventHandler)
        m_pWebBrowserEventHandler=pEventHandler;
}

void DuiLib::CWebBrowserUI::Refresh2( int Level )
{
    CVariant vLevel;
    vLevel.vt=VT_I4;
    vLevel.intVal=Level;
    m_pWebBrowser2->Refresh2(&vLevel);
}

void DuiLib::CWebBrowserUI::SetAttribute( LPCTSTR pstrName, LPCTSTR pstrValue )
{
    if (_tcscmp(pstrName, _T("homepage")) == 0)
    {
        m_sHomePage = pstrValue;
    }
    else if (_tcscmp(pstrName, _T("autonavi"))==0)
    {
        m_bAutoNavi = (_tcscmp(pstrValue, _T("true")) == 0);
    }
    else
        CActiveXUI::SetAttribute(pstrName, pstrValue);
}

void DuiLib::CWebBrowserUI::NavigateHomePage()
{
    if (!m_sHomePage.IsEmpty())
        this->NavigateUrl(m_sHomePage);
}

void DuiLib::CWebBrowserUI::NavigateUrl( LPCTSTR lpszUrl )
{
    if (m_pWebBrowser2 && lpszUrl)
    {
        m_pWebBrowser2->Navigate((BSTR)SysAllocString(T2BSTR(lpszUrl)),NULL,NULL,NULL,NULL);
    }
}

LPCTSTR DuiLib::CWebBrowserUI::GetClass() const
{
    return _T("WebBrowserUI");
}

LPVOID DuiLib::CWebBrowserUI::GetInterface( LPCTSTR pstrName )
{
    if( _tcscmp(pstrName, DUI_CTR_WEBBROWSER) == 0 ) return static_cast<CWebBrowserUI*>(this);
    return CActiveXUI::GetInterface(pstrName);
}

void DuiLib::CWebBrowserUI::SetHomePage( LPCTSTR lpszUrl )
{
    m_sHomePage.Format(_T("%s"),lpszUrl);
}

LPCTSTR DuiLib::CWebBrowserUI::GetHomePage()
{
    return m_sHomePage;
}

void DuiLib::CWebBrowserUI::SetAutoNavigation( bool bAuto /*= TRUE*/ )
{
    if (m_bAutoNavi==bAuto)    return;

    m_bAutoNavi=bAuto;
}

bool DuiLib::CWebBrowserUI::IsAutoNavigation()
{
    return m_bAutoNavi;
}

STDMETHODIMP DuiLib::CWebBrowserUI::QueryService( REFGUID guidService, REFIID riid, void** ppvObject )
{
    HRESULT hr = E_NOINTERFACE;
    *ppvObject = NULL;

    if ( guidService == SID_SDownloadManager && riid == IID_IDownloadManager)
    {
        *ppvObject = this;
        return S_OK;
    }

    return hr;
}

HRESULT DuiLib::CWebBrowserUI::RegisterEventHandler( BOOL inAdvise )
{
    CComPtr<IWebBrowser2> pWebBrowser;
    CComPtr<IConnectionPointContainer>  pCPC;
    CComPtr<IConnectionPoint> pCP;
    HRESULT hr = GetControl(IID_IWebBrowser2, (void**)&pWebBrowser);
    if (FAILED(hr))
        return hr;
    hr=pWebBrowser->QueryInterface(IID_IConnectionPointContainer,(void **)&pCPC);
    if (FAILED(hr))
        return hr;
    hr=pCPC->FindConnectionPoint(DIID_DWebBrowserEvents2,&pCP);
    if (FAILED(hr))
        return hr;

    if (inAdvise)
    {
        hr = pCP->Advise((IDispatch*)this, &m_dwCookie);
    }
    else
    {
        hr = pCP->Unadvise(m_dwCookie);
    }
    return hr; 
}

DISPID DuiLib::CWebBrowserUI::FindId( IDispatch *pObj, LPOLESTR pName )
{
    DISPID id = 0;
    if(FAILED(pObj->GetIDsOfNames(IID_NULL,&pName,1,LOCALE_SYSTEM_DEFAULT,&id))) id = -1;
    return id;
}

HRESULT DuiLib::CWebBrowserUI::InvokeMethod( IDispatch *pObj, LPOLESTR pMehtod, VARIANT *pVarResult, VARIANT *ps, int cArgs )
{
    DISPID dispid = FindId(pObj, pMehtod);
    if(dispid == -1) return E_FAIL;

    DISPPARAMS dispparams;
    dispparams.cArgs = cArgs;
    dispparams.rgvarg = ps;
    dispparams.cNamedArgs = 0;
    dispparams.rgdispidNamedArgs = NULL;

    return pObj->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &dispparams, pVarResult, NULL, NULL);
}

HRESULT DuiLib::CWebBrowserUI::GetProperty( IDispatch *pObj, LPOLESTR pName, VARIANT *pValue )
{
    DISPID dispid = FindId(pObj, pName);
    if(dispid == -1) return E_FAIL;

    DISPPARAMS ps;
    ps.cArgs = 0;
    ps.rgvarg = NULL;
    ps.cNamedArgs = 0;
    ps.rgdispidNamedArgs = NULL;

    return pObj->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &ps, pValue, NULL, NULL);
}

HRESULT DuiLib::CWebBrowserUI::SetProperty( IDispatch *pObj, LPOLESTR pName, VARIANT *pValue )
{
    DISPID dispid = FindId(pObj, pName);
    if(dispid == -1) return E_FAIL;

    DISPPARAMS ps;
    ps.cArgs = 1;
    ps.rgvarg = pValue;
    ps.cNamedArgs = 0;
    ps.rgdispidNamedArgs = NULL;

    return pObj->Invoke(dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYPUT, &ps, NULL, NULL, NULL);
}

IDispatch* DuiLib::CWebBrowserUI::GetHtmlWindow()
{
    IDispatch* pDp =  NULL;
    HRESULT hr;
    if (m_pWebBrowser2)
        hr=m_pWebBrowser2->get_Document(&pDp);

    if (FAILED(hr))
        return NULL;

    CComQIPtr<IHTMLDocument2> pHtmlDoc2 = pDp;

    if (pHtmlDoc2 == NULL)
        return NULL;

    hr=pHtmlDoc2->get_parentWindow(&_pHtmlWnd2);

    if (FAILED(hr))
        return NULL;

    IDispatch *pHtmlWindown = NULL;
    hr=_pHtmlWnd2->QueryInterface(IID_IDispatch, (void**)&pHtmlWindown);
    if (FAILED(hr))
        return NULL;

    return pHtmlWindown;
}

IWebBrowser2* DuiLib::CWebBrowserUI::GetWebBrowser2( void )
{
    return m_pWebBrowser2;
}

HRESULT STDMETHODCALLTYPE DuiLib::CWebBrowserUI::QueryStatus( __RPC__in_opt const GUID *pguidCmdGroup, ULONG cCmds, __RPC__inout_ecount_full(cCmds ) OLECMD prgCmds[ ], __RPC__inout_opt OLECMDTEXT *pCmdText )
{
    HRESULT hr = OLECMDERR_E_NOTSUPPORTED;
    return hr;
}

HRESULT STDMETHODCALLTYPE DuiLib::CWebBrowserUI::Exec( __RPC__in_opt const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, __RPC__in_opt VARIANT *pvaIn, __RPC__inout_opt VARIANT *pvaOut )
{
    HRESULT hr = S_OK;

    if (pguidCmdGroup && IsEqualGUID(*pguidCmdGroup, CGID_DocHostCommandHandler))
    {

        switch (nCmdID) 
        {

        case OLECMDID_SHOWSCRIPTERROR:
            {
                IHTMLDocument2*             pDoc = NULL;
                IHTMLWindow2*               pWindow = NULL;
                IHTMLEventObj*              pEventObj = NULL;
                BSTR                        rgwszNames[5] = 
                { 
                    SysAllocString(L"errorLine"),
                    SysAllocString(L"errorCharacter"),
                    SysAllocString(L"errorCode"),
                    SysAllocString(L"errorMessage"),
                    SysAllocString(L"errorUrl")
                };
                DISPID                      rgDispIDs[5];
                VARIANT                     rgvaEventInfo[5];
                DISPPARAMS                  params;
                BOOL                        fContinueRunningScripts = true;
                int                         i;

                params.cArgs = 0;
                params.cNamedArgs = 0;

                // Get the document that is currently being viewed.
                hr = pvaIn->punkVal->QueryInterface(IID_IHTMLDocument2, (void **) &pDoc);    
                // Get document.parentWindow.
                hr = pDoc->get_parentWindow(&pWindow);
                pDoc->Release();
                // Get the window.event object.
                hr = pWindow->get_event(&pEventObj);
                // Get the error info from the window.event object.
                for (i = 0; i < 5; i++) 
                {  
                    // Get the property's dispID.
                    hr = pEventObj->GetIDsOfNames(IID_NULL, &rgwszNames[i], 1, 
                        LOCALE_SYSTEM_DEFAULT, &rgDispIDs[i]);
                    // Get the value of the property.
                    hr = pEventObj->Invoke(rgDispIDs[i], IID_NULL,
                        LOCALE_SYSTEM_DEFAULT,
                        DISPATCH_PROPERTYGET, &params, &rgvaEventInfo[i],
                        NULL, NULL);
                    SysFreeString(rgwszNames[i]);
                }

                // At this point, you would normally alert the user with 
                // the information about the error, which is now contained
                // in rgvaEventInfo[]. Or, you could just exit silently.

                (*pvaOut).vt = VT_BOOL;
                if (fContinueRunningScripts)
                {
                    // Continue running scripts on the page.
                    (*pvaOut).boolVal = VARIANT_TRUE;
                }
                else
                {
                    // Stop running scripts on the page.
                    (*pvaOut).boolVal = VARIANT_FALSE;   
                } 
                break;
            }
        default:
            hr = OLECMDERR_E_NOTSUPPORTED;
            break;
        }
    }
    else
    {
        hr = OLECMDERR_E_UNKNOWNGROUP;
    }
    return (hr);
}