Howto: Ignoring web browser certificate errors in a webbrowser host

The webbrowser queries host services via IServiceProvider implemented on the ActiveX host. One of the services is IHttpSecurity, which can be used to override the certificate problem dialog.

Security warning: ignoring security problems can compromise your application.

IHttpSecurity is derived from IWindowForBindingUI, so the host needs to implement it too.

In Windows forms, customizing certificate error handling involves the following:

  • derive a class from WebBrowser
  • create a nested class derived from WebBrowser.WebBrowserSite (the only way you can derive from the nested class)
  • overwrite CreateWebBrowserSiteBase and return a new instance of your webbrowser site.
  • implement IServiceProvider on the webbrowser site
  • implement IServiceProvider.QueryService so it returns an IHttpSecurity imepleemntation when the IHttpSecurity service is requested
  • handle IHttpSecurity.OnSecurityProblem and return S_OK (warning: undocumented code, won’t work in IE6)
  • use the new webbrowser in the form

Sample code:

    public partial class Form1 : Form
        public Form1()
        private void webBrowser1_DocumentCompleted(object sender,
            WebBrowserDocumentCompletedEventArgs e)
            if (e.Url.ToString() == “about:blank”)
                //create a certificate mismatch
    public interface UCOMIServiceProvider
        [return: MarshalAs(UnmanagedType.I4)]
        int QueryService(
            [In] ref Guid guidService,
            [In] ref Guid riid,
            [Out] out IntPtr ppvObject);
    public interface IWindowForBindingUI
        [return: MarshalAs(UnmanagedType.I4)]
        int GetWindow(
            [In] ref Guid rguidReason,
            [In, Out] ref IntPtr phwnd);
    public interface IHttpSecurity
        //derived from IWindowForBindingUI
        [return: MarshalAs(UnmanagedType.I4)]
        int GetWindow(
            [In] ref Guid rguidReason,
            [In, Out] ref IntPtr phwnd);
        int OnSecurityProblem(
            [In, MarshalAs(UnmanagedType.U4)] uint dwProblem);
    public class MyWebBrowser : WebBrowser
        public static Guid IID_IHttpSecurity
            = new Guid(“79eac9d7-bafa-11ce-8c82-00aa004ba90b”);
        public static Guid IID_IWindowForBindingUI
            = new Guid(“79eac9d5-bafa-11ce-8c82-00aa004ba90b”);
        public const int S_OK = 0;
        public const int S_FALSE = 1;
        public const int E_NOINTERFACE = unchecked((int)0x80004002);
        public const int RPC_E_RETRY = unchecked((int)0x80010109);
        protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
            return new MyWebBrowserSite(this);
        class MyWebBrowserSite : WebBrowserSite,
            private MyWebBrowser myWebBrowser;
            public MyWebBrowserSite(MyWebBrowser myWebBrowser)
                this.myWebBrowser = myWebBrowser;
            public int QueryService(ref Guid guidService
                , ref Guid riid
                , out IntPtr ppvObject)
                if (riid ==IID_IHttpSecurity)
                    ppvObject= Marshal.GetComInterfaceForObject(this
                        , typeof(IHttpSecurity));
                    return S_OK;
                if (riid == IID_IWindowForBindingUI)
                    ppvObject = Marshal.GetComInterfaceForObject(this
                        , typeof(IWindowForBindingUI));
                    return S_OK;
                ppvObject = IntPtr.Zero;
                return E_NOINTERFACE;
            public int GetWindow(ref Guid rguidReason
                , ref IntPtr phwnd)
                if (rguidReason == IID_IHttpSecurity
                    || rguidReason == IID_IWindowForBindingUI)
                    phwnd = myWebBrowser.Handle;
                    return S_OK;
                    phwnd = IntPtr.Zero;
                    return S_FALSE;
            public int OnSecurityProblem(uint dwProblem)
                //ignore errors
                //undocumented return code, does not work on IE6
                return S_OK;
For sample code in providing the service using MFC, check Handle NewWindow3 and ShowModalDialog in CHtmlView. The way to implements IHttpSecurity is similar to how the article exposes the INewWindowManager service to the webbrowser control.
Posted in C#, MFC, Microsoft, Visual Studio, Webbrowser control | Tagged , , , , , | 20 Comments

When you get a System.BadImageFormatException. maybe you indeed have a bad system image.

I am getting a StackOverflowException with two functions repeating on the call stack, one is the constructor of System.BadImageFormatException, another is System.Environment.GetResourceStringLocal.  Since the call that throws the stack overflow is to a web service proxy defined in the same project as the application, there isn’t a 32bit/64bit mismatch here (32bit machine with every project targeting x86), unlike almost all other discussions on the internet about this exception.

After inspecting Fusion and event logs and finding nothing suspicious, I decided to treat it as a real bad image problem and reinstalled .Net. Ура! The exception went away after reinstalling.

Sometimes, the exception name isn’t misleading.

PS a similar question was closed as too vague on stackoverflow.

Posted in Microsoft, Visual Studio | Tagged , , | 1 Comment

How to restart Windows Explorer programmatically using Restart manager

For shell extension programmers, restart Windows Explorer is one of steps in their setup programs. A programmer may also want to force some shell setting changes that would only be read by Explorer on start up. For example, this posts is inspired by a programmer who want to toggle task bar layout automatically depending on the screen resolution, and is used to demonstrate the new Windows Vista restart manager API like RmStartSession, RmRegisterResources, RmGetList, RmShutdown, RmRestart and RmEndSession.

Traditionally restarting explorer is a hackish process. Most of people kill the process by brutal force like taskkill or TerminateProcess, however this approach produces a pretty mess, and if HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\AutoRestartShell is on, Windows would restart explorer. This is not want the user want – not only because changes in the previous explorer session are only saved during a clean shutdown, but the restarting also needs to be delayed to allow some time to change the task bar layout. A grace way to terminate would be to send WM_QUIT, or use Vista’s new restart manager API.

Restart manager is introduced in Vista to minimize system restarts when installing patches. For example, you can now upgrade IE without a restart. Here it is merely used to restart a particular program, but it has more interesting usage, such as restarting an application after crash.

The first step of restarting explorer would be registering the main explorer process for restarting. RmRegisterResources can be used to restart a process in a session started by RmStartSession, however the machine could have extra explorer processes if the “launch folder in a separate process” setting is on, or if other users are logged in. Here the code loop through all explorer processes and try to find the oldest one for restarting purpose. This is assuming only one user is going to use the computer, an IsProcessInSession check is needed if multiple users would be logged on concurrently.

//returns the process id and create time for the oldest explorer.exe 
RM_UNIQUE_PROCESS GetExplorerApplication()
    RM_UNIQUE_PROCESS  result={0};
    DWORD bytesReturned=0;
    DWORD processIdSize=4096;
    std::vector<DWORD> processIds;
    }    std::for_each(processIds.begin(), processIds.end(), [&result] (DWORD processId) {
                                   FALSE, processId);
         if (hProcess) {
            std::wstring imageName;
            if(GetProcessImageFileName (hProcess,(LPWSTR),4096)>0)
                    //this is assmuing the user is not running elevated and won't see explorer processes in other sessions
                    FILETIME ftCreate, ftExit, ftKernel, ftUser;
                    if (GetProcessTimes(hProcess, &ftCreate, &ftExit,&ftKernel, &ftUser))
                        else if(CompareFileTime(&result.ProcessStartTime,&ftCreate)>0)
    return result;

Next step would be telling the restart manager to request a shutdown via RmShutdown and restart via RmRestart after some registry tweak:

//taskbar position calculating code omitted
    DWORD dwSession=0;
    WCHAR szSessionKey[CCH_RM_SESSION_KEY+1] = { 0 };
    DWORD dwError = RmStartSession(&dwSession, 0, szSessionKey);
    if (dwError == ERROR_SUCCESS) {
        RM_UNIQUE_PROCESS rgApplications[1]={GetExplorerApplication()};
        DWORD dwReason;
        UINT nProcInfoNeeded;
        UINT nProcInfo = 10;
        RM_PROCESS_INFO rgpi[10];
        dwError = RmGetList(dwSession, &nProcInfoNeeded,
                       &nProcInfo, rgpi, &dwReason);
        if(dwReason==RmRebootReasonNone)//now free to restart explorer
            RmShutdown(dwSession,RmForceShutdown,NULL);//important, if we change the registry before shutting down explorer will override our change
            //using undocumented setting structure, could break any time
            //edge setting is stored at HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\StuckRects2!Settings
            HKEY hKey={0};
            DWORD result=0;
            result=::RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StuckRects2"),
                    0, KEY_READ|KEY_WRITE, &hKey) ;
            if (result== ERROR_SUCCESS)
                std::vector<BYTE> data;
                TCHAR settingValue[]= _T("Settings");
                DWORD dwKeyDataType=0;
                DWORD dwDataBufSize=data.size();
                result=::RegQueryValueEx(hKey,settingValue, NULL, &dwKeyDataType,
                    (LPBYTE), &dwDataBufSize);
                    result=::RegQueryValueEx(hKey,settingValue, NULL, &dwKeyDataType, 
                        (LPBYTE), &dwDataBufSize);
                    switch ( dwKeyDataType )
                        case REG_BINARY:
                                BYTE taskbarPosition=data[12];
                                RECT* taskbarRect=(RECT*)&data[24];
                                CopyRect (taskbarRect,&abd.rc);
                                result=::RegSetValueEx(hKey,settingValue,0,REG_BINARY,(LPBYTE), dwDataBufSize);
                ::RegCloseKey( hKey );
            RmRestart (dwSession,0,NULL);

Finally the RmEndSession function is called to free up resources. For other lockable resource like files the steps to restart affected processes are similar. This API can also be used to write restart manager custom actions if the installer authoring software does not support the restart manager.

Posted in enmsdn, Microsoft, Visual C++, Visual Studio | Tagged , , , | 7 Comments

How to: Migrating a CLR console Visual C++ project to Windows Forms

Note: Windows Forms programming in new development is discouraged by Microsoft at this point as Microsoft wants to make full use of hardware accelerated drawing instead of using the CPU-intensive GDI. But maintaining old Windows Forms code in Visual C++ 2012 is still supported, GDI isn’t going anywhere anytime soon.

Visual C++ 2012 removed the Windows Forms project template and I see people scramble to find ways to create a Windows Forms project.  There is a walkaround that’s been around for years, that is, to convert a CLR console application to a Windows one, then add forms related code to the project.

The basic steps are listed at, conveniently named “How to suppress the console window for a managed extensions to Visual C++ Windows Forms application“. Yes, the need to convert a C++ console application to windows forms is that old, back all the way back in the managed extensions for C++  days.

So what I need to do to add Windows Forms support to a C++/CLI console application? Of course the System.Windows.Forms.dll reference is missing in a new console application, so I need to reference it:

  • In code:

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System::Windows::Forms;

  • Or In IDE:
    • Select the project in Solution Explorer
    • On the Project menu or the context menu of the project node, select Properties
    • In the Property Pages dialog box, expand the Common Properties node, select Framework and References, and then click Add New Reference.
    • Find and add System.Windows.Forms in the list of available references.

In reality the Windows Forms Designer generates a lot of layout code that uses System.Drawing types like Point and Size, so I need to repeat the steps for System.Drawing.

Next the console window needs to be suppressed. The C++/CLI console project template in fact does not specify an entry point, so compiler guesses because a main function exists, the project is a console application. A Windows Forma application’s entry point has the same signature with the main function, therefore the /subsystem setting of the project needs to be changed to Windows:

  • Go back to the project’s Property Pages dialog box.
  • Click the Linker folder on the type.
  • Click the System property page.
  • Change the SubSystem property to Windows.

Ready? Not yet. The compiler is now trying to find a WinMain function, and throws LNK2028 and  LNK2019 when it can’t find the entry point, which of course isn’t there. I am not interested in writing one as I prefer to keep the nice args command line parameter of an array<String^>^ type , so I need to tell the compiler my entry point function is still main:

  • Go back to the the Linker folder.
  • Click the Advanced property page.
  • Change the Entry Point property to main.

We are almost here. Windows Forms needs an STA thread, so I have to add  [STAThreadAttribute] to the main function:

int main(array<System::String ^> ^args)

….. // wait did I add anything here? I guess not yet

Here you go,  a Windows Forms application that does nothing interesting.  Mmm, to make it a little more visual, I create a new Windows Form class named Form1 and run it in the main function:

//before main function
#include “Form1.h”
using namespace ProjectName;

//in the main function

// Create the main window and run it
Application::Run(gcnew Form1());

Yada! I have a Windows Forms application running now.

Posted in C++/CLI, enmsdn, Microsoft, Visual C++, Visual Studio | Tagged , , , | 3 Comments

Add the correct interface first in Adding an MFC Class from an ActiveX Control wizard.

In good old times aka VC6, if you want to use an ActiveX in MFC, the Components and Controls Gallery would generate all the properties and methods of an ActiveX and pull dependent types and create wrapper classes for them as well. And it was good. It magically knows the main class of the Windows Media Player ActiveX is CWMPPlayer4 and that GetCurrentMedia method returns CWMPMedia.

Welcome to the modern Visual C++. Now comes a new wizard that gives you options to choose interfaces to import from. At the same time you got to decide if you really need that many types from an ActiveX.  If you went the unfortunate path of Adding a Member Variable wizard in the dialog editor and somehow got a COCX1 class back, you don’t have the luxury to choose, and you end up with an CWnd wrapper class that does not really wrap up the properties and methods of the ActiveX. It is still good for early binding (like querying IWMPPlayer4 from the result of CWnd::GetControlUnknown) but if you plan to use late binding and MFC’s OLE support (hello COleException!),  you probably want to delete the COCX1 files and start over with the Adding a Class from an ActiveX Control wizard.

Good thing about the new Adding a Class from an ActiveX Control wizard is that most of time we don’t care about the majority of the types in the ActiveX’s type library. We are not going to call most of the ActiveX’s functionality anyways, so selecting what we would use makes sense. Bad thing is that now we don’t know the return type of a method from the generated classes if the return type is LPDISPATCH, lead to guesswork or fire up OLEView to look up the types in the ActiveX’s type library).

Now comes the worst part of the new wizard. The wizard somehow lost its ability to find the correct ActiveX control class and opt to use the first selected interface to generate a CWnd wrapper.  If you naturally click on the >> button to select all interfaces in the Windows Media Player ActiveX at once, you get a CWMPCdromCollection derived from CWnd. That  won’t work as the ActiveX does not implement the IWMPCdromCollection interfaces (undefined behavior can happen if you call the generated methods), and certainly the WMPCdromCollection class isn’t an insertable ActiveX.

Fortunately it is easy to avoid this issue if you add the ActiveX’s main interface first (e.g. IWMPPlayer4 for the Windows Media Player control) before adding the rest of interfaces, or correct the generated code for the first interface. That is, swap the CWnd and COleDispatchDriver code between the wrong class and the correct class for the main interface. It takes some time to find the correct class for the ActiveX control, however.

Side note: For code cleanness, you probably want to move the InvokeHelper code in the headers to cpp files like VC6 did. A good C++ refactoring tool can help that tremendously.

Posted in enmsdn, MFC, Microsoft, Microsoft Foundation Class Library, Visual C++, Visual Studio | Tagged , , , | Leave a comment

Howto: reset IE security zone settings programmatically

Internet Explorer 7 introduced the IInternetZoneManagerEx2 interface, which has a FixUnsecureSettings method to reset all security zone settings. Like all other IInternetZoneManager* interfaces, you can query this interface from the internet zone manager object:

IInternetZoneManagerEx2* pzoneManager=NULL;

HRESULT hr=CoCreateInstance(CLSID_InternetZoneManager ,NULL,CLSCTX_INPROC_SERVER,IID_IInternetZoneManagerEx2,(LPVOID*)&pzoneManager);
if(hr==S_OK && pzoneManager!=NULL)

There’s another CoInternetCreateZoneManager function to get the zone manager object’s IInternetZoneManager interface.

Posted in enmsdn, Microsoft, Visual C++, Visual Studio, Webbrowser control | Tagged , , | 1 Comment

What’s new in MFC/ATL 11 Beta

Note this post is on Visual Studio 11 Beta, you can download it from

Since Sinofsky posted about no desktop apps on Windows on ARM (WOA), it looks like MFC and ATL are going to support metro-style apps, although most ATL classes are not going to be compatible with metro style apps.

#if !defined(_M_IX86) && !defined(_M_AMD64) && !defined(_M_ARM)
#error Compiling for unsupported platform. Only x86, x64 and ARM platforms are supported by MFC.

DAO support for ARM is missing, just like the lack of DAO support for 64 bit apps. Jet was deprecated a while ago, no surprise here.

You can now decide whether you want MFC’s feature pack code when static linking.

Added support for RichEdit 4.1. About time.

MFC now introduces dependency on uxtheme.dll and dwmapi.dll. Not sure why applications need to check MFC for DWM status.

Lots of defensive programming added to OLE and ActiveX document support. MFC developers have too much free time? I thought ActiveX document was dead. Or maybe someone else is pushing those changes, like Adobe or the Office team. Or Microsoft’s security police. Lots of function prototype changes, probably because MFC headers need to pass static code analysis. Some other security improvements, like loading known Dlls only from system path, skipping DLL search paths.  CDatabase now stores the connection string in memory in encrypted form.

Some new OS API exposure like CFile gets a lot more NTFS-specific attributes. CFileDialog gets a pick non-system folder mode.

Some design changes are head-scratching, CPropertyPage gets a GetParentSheet function. Looks like the parent of the page may no longer be a property sheet.

In summary, there isn’t much code change in MFC. The demands I see from community forums are mostly on C++11, which is not surprisingly the focus of the Visual C++ team in this release and probably will continue for a while.

Posted in Visual C++ | Tagged , , , | Leave a comment

Choosing formats when putting data on clipboard

The topic is from a forum discussion at

Generally an application should provide data in as many formats as possible so more applications can recognize the data. For example, IE stores text data in CF_UNICODETEXT, CF_TEXT and CF_HTML formats.

Because a lot of application would stop enumerating the clipboard on first supported format, to avoid data lose in round trips, clipboard formats that contain the most information should be placed on the clipboard first, followed by less descriptive formats. For example, CF_HTML first, CF_UNICODETEXT second and CF_TEXT last. Sometimes you get to choose from the paste format (e.g. paste special in Microsoft Word), but that’s the exception, not many program can paste the format that is not the first supported format (e.g. you don’t have paste special in Microsoft Paint).

Of course sometimes you want to limit, say, the format being exposed to the clipboard, e.g. when copying code from Visual Studio but expect the code to make a round trip back to Visual Studio without the formatting, then you may want to put a less descriptive format first. 

If using the webbrowser control as the text editor, you can remove the formatting in pasting by implementing OnFilterDataObject.


Posted in enmsdn, Webbrowser control | Tagged | Leave a comment

What’s new in Windows 8 Developer Preview SDK headers

This is by no means a complete list but just some observation on files that caught my eye. Some are just regular header file updates for Windows 7 and does not necessary require Windows 8. Some other APIs moved to header files with more readable names.

Improvements are focused, of course, in natural input, efficiency, gaming experience and IE. You can hear the silence scream of “Tablet!Tablet!Tablet!” here. Note Windows 8 is still a developer preview and there is no guarantee any new feature will survive the final cut or there won’t be new API for existing features add in Beta/RC/Gold.


There is no improvement in the GDI-based shell common controls. No surprise here. The new UI would be based on WinRT and will use GPU to render instead of CPU. There are COM API for printing, which is traditionally performed via GDI.

A lot of Direct2D and Direct3D improvements. XAudio2 added and battery/pad support  added to XInput. Improvement in 3D rendering, device removal during capturing and stream seeking in Windows Media Foundation. API for H264 codec.


Header guard for IE5.01 or lower are removed. Building for Windows 2000 is now practically impossible. Some header guard switched to NTDDI_VERSION. There is A new camera UI control based on COM. Somehow the version guard of Shell_NotifyIconGetRect is lost, this might be a header file bug.


Lots of IE 10 APIs and HTML 5 support. ActiveScript optimized for multiple instance and webworker. Also there is a new IActiveScriptContext interface to get url, line and offset of the script. New timeout configuration in WinInet. ActiveX filtering, and options to enable/disable audio/video plugins added for IE security zones.


Accessibility for windowless controls and lots of UI automation improvements, including grid and spreadsheet types. Candidate list integration and async document support with Text Service Framework. ARM support to .Net APIs.  A lot of pointer device and touch messages, notification and drawing.

Posted in enmsdn, Microsoft, Visual C++ | Tagged , , , , , | Leave a comment

Where is the forum for Internet Explorer?

People get confused by various Microsoft IE forum sites so here is the steps to find the forum closer to IE related questions

Basically, the mentality of different Microsoft forum brand is:

MSDN: How can my software do something on my customers’ machines.

Technet: How can I manage things on machines in my network.

Answers: How can I do something on my own machine.

So for the case involving IE:

  1. using IE
  2. manage IE on someone else’s machine, or IE behaves abnormally only when the IE settings is managed by the network administrator
  3. Writing IE-aware software or IE-aware web sites

What about other tasks?

  1. I have problem with an IE add-on
    contact the support channel of the add-on. For example if there is a problem when viewing PDF in IE, most likely you need to visit the Adobe Reader forum at A question that occurs only after installing Google ToolBar should be posted to Google’s help groups.
  2. I see an error message in IE when visiting a web site
    does the error message appear when you switch to another web browser?

    1. Yes
      Contact the author of the web site

      1. But I am the author of the web site!
        Then try ask in a forum that covers the server programming framework, for example, visit if you have ASP.Net errors.
    2. No
      Run IE in no-addon mode(shortcut can be found in programs->accessories), is the problem still there?

      1. Yes
        Do you see this error when visiting other web sites?

        1. Yes
        2. No
          Contact the author of the web site

          1. But I am the author of the web site!
            Then visit and remember to include your web site’s link when asking
      2. No, where do I find the faulty add-on?
        Tools->Manage addons, and disable one-by-one, I guess. Those experts in probably have more experience in known faulty add-ons.
  3. IE tells me there is a script error on the web site
    Does this problem occur regardless which web sites IE is showing?

    1. Yes
      Visit Oh, and if you are going to do a repair install of IE before asking, remember to turn antivirus off.
    2. No, the script error only occur on certain web sites
      Are you the author of the web site involved?
      1. No
        Contact the authors of the web sites.

        1. The author cannot be found or I can’t wait the author to release an update
          Add the web site to the compatibility view list to see if the site works in old browser emulation mode.
      2. Yes, I am the author
        If you can reproduce your problem in no-addon mode, visit 
Posted in Uncategorized | Tagged , | Leave a comment