ActiveX development for browser plug-ins (1)

Source: Internet
Author: User

Generally, it is recommended that Web applications do not use browser plug-ins as much as possible, because it involves security issues and affects user installation (or automatic download and registration installation) experience. If you have special requirements (such as financial business data interaction involving data security and interaction with local devices only through plug-ins), you can use them with caution.

Browser plug-ins can be divided into two main camps: plug-ins supported by IE and plug-ins not supported by IE. Originally in the Netscape era, browser plug-ins have a public specification (npapi). At first, all browsers supported this specification, including IE. Later, for commercial reasons, Microsoft's ie no longer supported the npapi. Instead, it developed its own com-based ActiveX system, but this system refused to support non-ie browsers. Therefore, the current situation is basically that IE only supports ActiveX controls, while Firefox, chrome and other browsers only support another type of interfaces (XP com or npapi ). To implement a Web plug-in, you must at least consider the aceivex version supported by IE and the plug-in version not supported by IE (flash and Other plug-ins are different for IE and non-ie browsers ).

ActiveX development can be implemented in C #, VB, C ++, and other languages. You can use both ATL and MFC to develop ActiveX using C ++. The ATL ActiveX output file is small and suitable for network transmission, but the development complexity is slightly higher. The MFC ActiveX output file is slightly larger (with the necessary mfc dll), but it is easy to use. This article mainly introduces ActiveX development based on MFC.

1. Create a project and add an Interface

Create an MFC ActiveX Control Project in vs.net 2008:

Click "OK". The following dialog box is displayed:

Click "Next" until the "control settings" tab:

As this example only demonstrates ActiveX that only provides function interfaces not based on the interface, select "(none)" for "create Control Based on. Click "finish" to create the project. The file structure is as follows:

Right-click the project name and select "properties". In the Project Properties dialog box, configure "all deployments. On the "deployments properties-> General" tab, select "use MFC in a static library" for "use of MFC" to automatically package the relevant libraries of MFC and controls during compilation. The selection of "Character Set" depends on the specific situation. Note that "Unicode Character Set" and "Mulity-Byte Character Set" are completely different in character processing (character encoding is different, multibytetowidechar or widechartomultibyte conversion is required ).

 
Note:When you create an MFC ActiveX control, the. Def file is automatically added to the project and associated with it. If the compiled OCX fails to be registered after the configuration information is changed or the system prompts that the entrypoint cannot be found, check whether the module definition file of linker-> input is correctly configured, under normal circumstances, it is automatically configured, such:

 

Next, you can add the interface methods and attributes for external interaction in ActiveX. Select "Class View" and Right-click "mytestactivexlib-> _ dmytestactivex". In the pop-up menu, you can select Add function or add property to add interface methods or interface properties:

Here we defineLong addfun (long num1, long num2)For example, add menthod as shown in:

Click Finish to find the newly added interface function in the "mytestactivexctrl. cpp" file.Code:

Complete the custom business logic in the function body.

 

Ii. Implement Security Interfaces

After the above project is compiled, the ocx file can be generated. The ocx file can be embedded into HTML and run in IE. However, if the corresponding page of OCX is placed on a real Web server, ie will prompt "no relevant attribute, you need to set information such as initialization and script running security. This is because ActiveX needs to be executed on remote IE and Security interfaces must be implemented. For control initialization and Script Security Issues, let's talk about IObjectSafety and the MicrosoftArticleA detailed description is provided.

For Activex written by ATL, You can implement IObjectSafety. Here is a detailed description of the security interface implemented by ATL.

For Activex written by MFC, you can modify the Registry to implement control security. Microsoft also provides a detailed document description. The specific implementation steps are as follows:

1. Add the cathelp. h and cathelp. cpp files to the project. The contents are as follows.

Cathelp. h

 # include  "  comcat. h   "  //   helper function to create a component category and associated   //   description  hresult createcomponentcategory (catid, wchar *  catdescription);   //   helper function to register a CLSID as belonging to a component   //   Category   hresult registerclsidincategory (refclsid CLSID, catid);   //   hresult unregisterclsidincategory-Remove entries from the registry  hresult unregisterclsidincategory (refclsid CLSID, catid); 

Cathelp. cpp

# Include "  Stdafx. h  "  # Include  "  Comcat. h  "  # Include  "  Strsafe. h  "  # Include  "  Objsafe. h  "  // Hresult createcomponentcategory-used to register ActiveX control as safe Hresult createcomponentcategory (catid, wchar * Catdescription) {icatregister * PCR = NULL; hresult HR = S_ OK; HR = Cocreateinstance (clsid_stdcomponentcategoriesmgr, null, clsctx_inproc_server, iid_icatregister ,(  Void **)& PCR );  If  (Failed (HR ))  Return  HR; //  Make sure the hkcr \ component categories \ {... catid ...}  //  Key is registered.  Categoryinfo catinfo; catinfo. catid = Catid; catinfo. lcid = Zero X 0409 ; //  English  Size_t Len;  //  Make sure the provided description is not too long.  // Only copy the first 127 characters if it is.  //  The second parameter of stringcchlength is the maximum  //  Number of characters that may be read into catdescription.  //  There must be room for a null-Terminator. The third parameter  //  Contains the number of characters excluding the null-Terminator. HR = stringcchlength (catdescription, strsafe_max_cch ,& Len );  If (Succeeded (HR )){  If (LEN> 127  ) {Len = 127  ;}}  Else  {  //  Todo: Write an error handler;  }  //  The second parameter of stringcchcopy is 128 because you need  // Room for a null-Terminator. HR = stringcchcopy (catinfo. szdescription, Len + 1  , Catdescription );  //  Make sure the description is NULL terminated. Catinfo. szdescription [Len + 1 ] = '  \ 0  '  ; HR = PCR-> registercategories ( 1 ,& Catinfo); PCR ->Release ();  Return  HR ;}  //  Hresult registerclsidincategory-  //  Register your component categories Information  Hresult registerclsidincategory (refclsid CLSID, catid ){  //  Register your component categories information. Icatregister * PCR = NULL; hresult HR = S_ OK; HR =Cocreateinstance (clsid_stdcomponentcategoriesmgr, null, clsctx_inproc_server, iid_icatregister ,(  Void **)& PCR );  If  (Succeeded (HR )){  //  Register this category as being "implemented" by the class. Catid rgcatid [ 1  ]; Rgcatid [  0 ] = Catid; HR = PCR-> registerclassimplcategories (CLSID, 1 , Rgcatid );}  If (PCR! = Null) PCR -> Release ();  Return  HR ;}  //  Hresult unregisterclsidincategory-Remove entries from the Registry  Hresult unregisterclsidincategory (refclsid CLSID, catid) {icatregister * PCR = NULL; hresult HR = S_ OK; HR =Cocreateinstance (clsid_stdcomponentcategoriesmgr, null, clsctx_inproc_server, iid_icatregister ,(  Void **)& PCR );  If  (Succeeded (HR )){  //  Unregister this category as being "implemented" by the class. Catid rgcatid [ 1  ]; Rgcatid [  0 ] = Catid; HR = PCR-> unregisterclassimplcategories (CLSID, 1 , Rgcatid );}  If (PCR! = Null) PCR -> Release ();  Return  HR ;} 

Note: The code in cathelp. cpp is based on the Unicode Character Set. Therefore, if the project configuration is changed to multi-byte character set, you need to modify the code in cathelp. cpp; otherwise, the Code cannot be compiled;

 

2. In the mytestactivex. cpp file, addClsid_safeitemDefinition:

The value of clsid_safeitem is in accordance with xxxctrl. cpp (mytestactivexctrl. cpp in this example)Implement_olecreate_ex(In fact, it is ActiveX classid ). In this example, the mytestactivexctrl. cpp FileImplement_olecreate_exThe value is as follows:

Replace "0x1345c26b, 0xe979, 0x45a5, 0x99, 0x7d, 0x94, 0x27, 0xfb, 0x81, 0xe7, 0x7 "simply adding the" {"and"} "arc at the appropriate position becomes the clsid_safeitem value" 0x1345c26b, 0xe979, 0x45a5,{0x99, 0x7d, 0x94, 0x27, 0xfb, 0x81, 0xe7, 0x7}".

In addition, the following two files must be introduced at the beginning of the mytestactivex. cpp file for normal Compilation:

3. Modify mytestactivex. cppDllregisterserverAndDllunregisterserverFunction, the Code is as follows (just copy it ):

//  Dllregisterserver-adds entries to the system registry  Stdapi dllregisterserver (  Void  ) {Hresult hr;  //  Hresult used by safety functions  Afx_manage_state (_ afxmoduleaddrthis );  If (! Afxoleregistertypelib (AfxGetInstanceHandle (), _ tlid ))  Return  Resultfromscode (selfreg_e_typelib );  If (!Coleobjectfactoryex: updateregistryall (true ))  Return  Resultfromscode (selfreg_e_class );  //  Mark the control as safe for initializing.  HR = Createcomponentcategory (catid_safeforinitializing, l  "  Controls safely initializable from persistent data!  "  );  If  (Failed (HR )) Return  HR; HR = Registerclsidincategory (clsid_safeitem, catid_safeforinitializing );  If  (Failed (HR ))  Return  HR;  //  Mark the control as safe for scripting.  HR = Createcomponentcategory (catid_safeforscripting, l  "  Controls safely Scriptable! "  );  If  (Failed (HR ))  Return  HR; HR = Registerclsidincategory (clsid_safeitem, catid_safeforscripting );  If  (Failed (HR ))  Return  HR;  Return  Noerror ;}  // Dllunregisterserver-removes entries from the system registry  Stdapi dllunregisterserver (  Void  ) {Afx_manage_state (_ afxmoduleaddrthis );  //  Security Entry for deleting controls. Hresult hR = Unregisterclsidincategory (clsid_safeitem, catid_safeforinitializing );  If  (Failed (HR ))  Return  HR;  //  Security Entry for deleting Control Scripts HR =Unregisterclsidincategory (clsid_safeitem, catid_safeforscripting );  If  (Failed (HR ))  Return  HR;  If (! Afxoleunregistertypelib (_ tlid, _ wvermajor, _ wverminor ))  Return  Resultfromscode (selfreg_e_typelib );  If (! Coleobjectfactoryex: updateregistryall (false ))  Return Resultfromscode (selfreg_e_class );  Return  Noerror ;} 

Note: In many examplesDllunregisterserverAs a result, when the control is uninstalled (regsvr32/u XXXX. ocx), an error occurred while calling the dllunregisterserver function of a XX ocx file. Error code: 0x80070002. The root cause isDllunregisterserverAn error occurred while deleting the Registry. An article in the "waxgourd0 column" described this in detail.

 

4. Click the resource file (resources-> mytestactivex. RC), right-click and choose view code from the shortcut menu to edit the resource file information and ensure the correctness of the following items:

A) The Block value is"040904e4"

B)OleselfregisterThe value is"\ 0"

C) after translation in varfileinfo, it corresponds to"0x0409,125 2"

 

So far, projects can be compiled, and the output OCX control can run normally .~~~

 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

MFC ActiveX development references:

    1. A complete ActiveX web control tutorial
    2. Enable an MFC ActiveX Control to self-register

Reference materials for ATL ActiveX development:

    1. Dongting scattered: COM component development practices (2)

Comprehensive references:

    1. Yang Feng-COM components and design applications
    2. Com Development Recommendation books (recommended by Dongting individual)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.