Click here to Skip to main content
Click here to Skip to main content

Word/Excel ActiveX Controls in ASP.NET

, 15 Jun 2012
Rate this:
Please Sign up or sign in to vote.
In this article, we create an ActiveX control for Word/Excel and the control is used in an ASP.NET application.

Output Image

Output Image

What is an ActiveX Control

ActiveX is a software component of Microsoft Windows. If you have Internet Explorer, then ActiveX is already installed on your computer. ActiveX controls are small programs, sometimes called add-ons that are used on the Internet. They can enhance your browsing experience.

You can decide whether or not you want to download ActiveX controls on a case by case basis. Some websites require you to install ActiveX controls to view or perform certain tasks on them, but there can be potential risks. Cybercriminals may develop their own ActiveX controls and can damage computers if users visit web pages that contain malicious ActiveX software.

When you visit a site that uses an ActiveX control, Internet Explorer asks if you want to install the ActiveX control. You can then choose to install the ActiveX control or learn about the risks. Click Don't run if you do not trust the website and publisher.

Steps to create an ActiveX control

Create a Blank Solution in Visual Studio

  1. Open Visual Studio -->File menu-->New Project-->Other Project Types-->Visual Studio Solutions--->Blank Solution
  2. Write Blank Solution "OtherControlSol" and select solution location-->then OK.

Create C# Windows control in Visual Studio

  1. Right click on Solution Explorer --->New Project-->Visual C# Windows control library, project name "ControlWordExcel".
  2. After adding a Windows Control library project, right click on control---> then rename the control "ControlWordExcel".
  3. Open AssemblyInfo.cs and set [assembly: ComVisible(true)].
  4. Right click on references folder--->click on Add References..., then select the following references: Microsoft.Office.Core in (COM tab), Microsoft.Office.Interop.Excel, and Microsoft.Office.Interop.Word in (.NET tab), all references version 12.0.0.0, Microsoft Office 12.0 Object Library (COM tab).
  5. Right click on ControWordExcel Project--->select Properties--->click on Signing tab.
  6. Output Image

  7. Set control size width:998, height:573 from control property.
  8. Add file open dialog on control from control toolbox.
  9. Check on Sign the assembly-->choose New-->Dialog box will appear -->Enter Password--->click OK.
  10. Visual Studio Tools menu--->Create Guid--->Option 4 (Registry Format), Click on copy-->Open ControlWordExcel.cs. Add ProgId, ClassInterface, Guid, and ComVisible.
  11. [ProgId("ControlWord.ControlWordExcel")]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [Guid("98BAE912-0171-4c9c-A4EC-FD5969E92D08")]
    [ComVisible(true)]
  12. Write code to call the user32.dll API functions FindWindow, SetParent, and SetWindowPos.
  13. #region "API Calling"
    
    /// <summary>
    /// Retrieves a handle to the top-level window whose
    /// class name and window name match the specified strings.
    /// </summary>
    /// <param name="strclassName">calss name</param>
    /// <param name="strWindowName">window class name</param>
    /// <returns>If the function succeeds, the return value is a handle to the window
    /// that has the specified class name and window name.</returns>
    
    [DllImport("user32.dll")]
    public static extern int FindWindow(string strclassName, string strWindowName);
    
    /// <summary>
    /// Changes the parent window of the specified child window.
    /// </summary>
    /// <param name="hWndChild">A handle to the child window</param>
    /// <param name="hWndNewParent">A handle to the new parent window. If this parameter
    /// is NULL, the desktop window becomes the new parent window.</param>
    /// <returns>If the function succeeds, the return value
    /// is a handle to the previous parent window</returns>
    
    [DllImport("user32.dll")]
    static extern int SetParent(int hWndChild, int hWndNewParent);
    
    /// <summary>
    /// Changes the size, position, and Z order of a child, pop-up, or top-level window. 
    /// These windows are ordered according to their appearance on the screen. 
    /// The topmost window receives the highest rank and is the first window in the Z order
    /// </summary>
    /// <param name="hWnd">A handle to the window</param>
    /// <param name="hWndInsertAfter">A handle to the window
    /// to precede the positioned window in the Z order.</param>
    /// <param name="X">position of the left side of the window</param>
    /// <param name="Y">position of the top of the window</param>
    /// <param name="cx">width of the window</param>
    /// <param name="cy">height of the window</param>
    /// <param name="uFlags">
    /// window sizing and positioning flags.
    /// SWP_DRAWFRAME(0x20):Draws a frame (defined in the window's class description) around the window
    /// SWP_NOMOVE(0x2):Retains the current position (ignores X and Y parameters)
    /// SWP_NOZORDER(0x4):Retains the current Z order (ignores the hWndInsertAfter parameter).
    /// </param>
    /// <returns>If the function succeeds, the return value is nonzero</returns>
    
    [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
    static extern bool SetWindowPos(int hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
    
    #endregion
  14. Use namespace System.Runtime.InteropServices. Create objects of MS Word Microsoft.Office.Interop.Word.Document and Microsoft.Office.Interop.Word.ApplicationClass document and application. Next object for MS Excel Microsoft.Office.Interop.Excel.Workbook and Microsoft.Office.Interop.Excel.ApplicationClass for Excel Workbook and application.
  15. //object for word
    public Microsoft.Office.Interop.Word.Document wDocument;
    public static Microsoft.Office.Interop.Word.ApplicationClass acWord = null;
    //object for excel
    public Microsoft.Office.Interop.Excel.Workbook eWorkBook;
    public static Microsoft.Office.Interop.Excel.ApplicationClass acExcel = null;
    
    public static int iWindow = 0; // Window Handle
    public static string sFileName = null; // Word or Excel File name
  16. Now write code to open Word or Excel in the control. OpenDocument takes two parameters sMyFileName and sAppType of type string. According to passing type, the application class object is created. Then call the FindWindow function takes two parameters: class name and window name. For MS-Word, use class name Opusapp and MS-Excel uses class name XLMAIN. The next parameter is null for window name.
  17. FindWindow returns a non zero value if success, pass this value in the SetParent function. Next call the Open function for Word or Excel according to sAppType, whose value is W or E. Next, pass all missing values by creating object oMissing = System.Reflection.Missing.Value;. Open for MS-Word takes value by ref, but in MS-Excel, the Open function is not required to pass ref. To view MS-Word, use property Visible=true and call the Activate() function of the Microsoft.Office.Interop.Word.ApplicationClass object. Same for the Microsoft.Office.Interop.Excel.ApplicationClass object, use property Visible=true and UserControl = true. Finally, call SetWindowPos to set Word or Excel application in control at proper location.

    /// <summary>
    /// Open selected word or excel file.
    /// </summary>
    /// <param name="sMyFileName">word or excel file name</param>
    /// <param name="sAppType">W for Word, E for Excel</param>
    public void OpenDocument(string sMyFileName,string sAppType)
    {
        sFileName = sMyFileName;
    
        //object for word
        if (acWord == null && sAppType=="W")
            { acWord = new Microsoft.Office.Interop.Word.ApplicationClass(); }
        //object for excel
        if (acExcel == null && sAppType == "E")
            { acExcel = new Microsoft.Office.Interop.Excel.ApplicationClass(); }
    
        if (wDocument != null) { try { CloseAndSave(sAppType); } catch { } }
    
        if (eWorkBook != null) { try { CloseAndSave(sAppType); } catch { } }
        // "Opusapp" for ms word.
        if (iWindow == 0 && sAppType == "W") { iWindow = FindWindow("Opusapp", null); }
        // "XLMAIN" for ms excel.
        if (iWindow == 0 && sAppType == "E") { iWindow = FindWindow("XLMAIN",null); }
    
        if (iWindow != 0)
        {
            //call SetParent function.
            SetParent(iWindow, this.Handle.ToInt32());
    
            object oFileName = sFileName;
            object oReadOnly = false;
            object oIsVisible = true;
            object oMissing = System.Reflection.Missing.Value;
    
            try
            {
                if (iWindow == 0) { throw new Exception(); }
                //object for word
                if (sAppType == "W")
                {
                    if (acWord.Documents == null && sAppType == "W") { throw new Exception(); }
    
                    if (acWord != null && acWord.Documents != null && sAppType == "W")
                    { wDocument = acWord.Documents.Open(ref oFileName, ref oMissing, 
                        ref oReadOnly, ref oMissing, ref oMissing, ref oMissing, 
                        ref oMissing, ref oMissing, ref oMissing, ref oMissing, 
                        ref oMissing, ref oIsVisible, ref oMissing, ref oMissing, 
                        ref oMissing, ref oMissing); }
    
                    if (wDocument == null && sAppType == "W") { throw new Exception(); }
                }
                //object for excel
                if (sAppType == "E")
                {
                    if (acExcel.Workbooks == null && sAppType == "E") { throw new Exception(); }
    
                    if (acExcel != null && acExcel.Workbooks != null && sAppType == "E")
                    { eWorkBook = acExcel.Workbooks.Open(sFileName, oMissing,
                        oReadOnly, oMissing, oMissing, oMissing, oMissing, 
                        oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); }
    
                    if (eWorkBook == null && sAppType == "E") { throw new Exception(); }
                }
            }
            catch { }
            try
            {
                //object for word
                if (sAppType == "W")
                {
                    acWord.Visible = true;
                    acWord.Activate();                        
                }
                //object for excel
                if (sAppType == "E")
                {
                    acExcel.Visible = true;
                    acExcel.UserControl = true;
                }
                // call SetWindowPos
                SetWindowPos(iWindow, this.Handle.ToInt32(), 0, 0, this.Bounds.Width, 
                             this.Bounds.Height, (0x4 | 0x2 | 0x20));
    
                OnResize(new EventArgs());
               
            }
            catch { MessageBox.Show("Error..."); }
            this.Parent.Focus();
        }
    }
  18. Write function to close Word or Excel application with save. For this, the CloseAndSave function takes a parameter sAppType of type string. According to this parameter, we call the function Save(), Close(), and Quit(). Finally assign a null value to the object and also pass zero value to the iWindow object of type int.
  19. /// <summary>
    /// Close and Save File.
    /// </summary>
    /// <param name="sAppType">W for Word, E for Excel</param>
    public void CloseAndSave(string sAppType)
    {
        try
        {
            object oMissing = false;
            if (sAppType == "W")
            {
                wDocument.Save();
                wDocument.Close(ref oMissing, ref oMissing, ref oMissing);
                acWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                acWord = null;
            }
            if (sAppType == "E")
            {
                eWorkBook.Save();
                eWorkBook.Close(oMissing, oMissing, oMissing);
                acExcel.Quit();
                acExcel = null;
            }
            iWindow = 0;
        }
        catch (Exception ex)
        { }
    }
  20. Now write file open dialog code. For this, create the BrowseFileDialog() function that takes a parameter sAppType of type string. According to type, set filter for the file open dialog, get filename, and call OpenDocument().
  21. /// <summary>
    /// call file open dialog to open file.
    /// </summary>
    /// <param name="sAppType">W for Word, E for Excel</param>
    /// <returns>return selected file name with location.</returns>
    public string BrowseFileDialog(string sAppType)
    {
        string sFName; string sFilterExtension = "";
        openFileDialog1.Multiselect = false;
        openFileDialog1.FileName = "";
        //object for word
        if (sAppType == "W") { sFilterExtension = "MS-Word Files (*.docx,*.doc,*.dot) |*.docx;*.doc;*.dot;"; }
        //object for excel
        if (sAppType == "E") { sFilterExtension = "MS-Excel Files (*.xlsx,*.xls,*.xot) |*.xlsx;*.xls;*.xot;"; }
        openFileDialog1.Filter = sFilterExtension;
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            sFName = openFileDialog1.FileName;
        }
        else return "";
    
        try
        { this.CloseAndSave(sAppType); }
        catch { }
        finally
        {
            //object for word
            if (sAppType == "W")
            {
                this.wDocument = null;
                acWord = null;
            }
            //object for excel
            if (sAppType == "E")
            {
                this.eWorkBook = null;
                acExcel = null;
            }
            iWindow = 0;
        }
        try
        {
            //open file word or excel.
            this.OpenDocument(sFName, sAppType);
        }
        catch (Exception ex) { String err = ex.Message; }
        return sFName;
    }
  22. Finally save and build the project, and view the .dll file in the Release or Debug folder. The next step is to register assembly with codebase.

Control Register (Regasm.exe)

The Assembly Registration tool reads the metadata within an assembly and adds the necessary entries to the Registry, which allows COM clients to create .NET Framework classes transparently. Create a Codebase entry in the Registry, use /codebase options. The Codebase entry specifies the file path for an assembly that is not installed in the Global Assembly Cache. To unregister, use the /u option.

Output Image

Create New Web Site

Open default.aspx and write code to display control.

Output Image

Create new JavaScript file

Create new jscontrol.js file on root location, to handle JavaScript functions related to the control.

Output Image

Finally build code and run the website.

Create Digital Certificate

The Certificate Creation tool generates X.509 certificates for testing purposes only. It creates a public and private key pair for digital signatures and stores it in a certificate file. This tool also associates the key pair with a specified publisher's name and creates an X.509 certificate that binds a user-specified name to the public part of the key pair.

  • -r Creates a self-signed certificate, -sv specifies the subject's .pvk private key file. The file is created if none exists.
  • -n Specifies the subject's certificate name. This name must conform to the X.500 standard. The simplest method is to specify the name in double quotes, preceded by CN=; for example, "CN=myName".
  • -b Specifies the start of the validity period. Defaults to the certificate's creation date (mm/dd/yyyy).
  • -e Specifies the end of the validity period date (mm/dd/yyyy). Defaults to 12/31/2039 11:59:59 GMT.

Open VS command prompt and type the makecert command to create a digital certificate, enter any password for digital certificate, press OK.

Output Image

The next step again will ask password type same, press ok.

Output Image

Go to Visual Studio command prompt location, and you will find three files: .cer, .pfx, and .pvk.

Signing Digital Certificate

The Sign Tool is a command-line tool that digitally signs files, verifies signatures in files, or time stamps files. signwizard launches the signing wizard. Only a single file can be specified for the file name command-line argument.

To sign a digital certificate for all files .dll, .msi, and .cab, repeat the same step for all files. Open the VS command prompt and type the signtool.exe signwizard command, press Enter. A wizard will appear and follow the below steps.

Note

First sign the .dll assembly file. Then sign the .msi setup file. Last, sign the .cab cabinet file.

Output Image

Click on Next and open the location of .dll, .msi, and .cab, then select Custom, again click on Next.

Output Image

Go to the Visual Studio command prompt location and select the .pvk file.

Output Image

Then enter the same key, then OK.

Output Image

Use the default algorithm and click Next.

Output Image

Enter same password key, press OK, click on Finish, the message box will appear to complete the signing process successfully.

Create C# Windows Setup project

  1. Right click on Solution Explorer --->New project, Setup project, name "SetupWordExcel".
  2. Output Image

  3. Add Files--> select ControlWordExcel.dll from control build location.
  4. Set Register property to vsdraCOM of ControlWordExcel.dll, the property vsdraCOM, the item will be registered as a COM object.
  5. Output Image

  6. Build project and find output in bin folder (Debug or Release).
  7. Repeat signtool wizard process to sign the SetupWordExcel.msi file.

Create CAB file

For cab file, use cabarc.exe. We are creating a cab file for the ActiveX control, we need the .inf file also.

  1. Create a .inf file named "ControlWordExcel.inf" and write code in file.
  2. Output Image

  3. We need to merge SetupWordExcel.msi and ControlWordExcel.inf files in the cabinet file for the ActiveX control.
  4. Download the CABARC.EXE file to click on link download.
  5. Paste SetupWordExcel.msi and ControlWordExcel.inf in CABARC.EXE location or as your location path.
  6. Output Image

  7. Finally open folder location of ControlWordExcel.cab. Repeat Signtool wizard process to sign the ControlWordExcel.cab file.

Publish or Deploy Website on IIS

  1. In Visual Studio, paste .cab file in your web project on root location.
  2. Right click on web project and publish your website.
  3. Install IIS on your computer.
  4. Publish code pasted in the "C:\Inetpub\wwwroot" folder. Set website default page, type your localhost URL in IE browser (like: http://localhost/,http://127.0.0.1/ or your computer IP http://xxx.xxx.xx.xx/).

ActiveX control setting

Open IE-->Tools menu-->Internet Options-->Security tab-->Custom Level.

Output Image

If you find any problems viewing the control, please add the URL in your trusted site zone in Security tab and unchecked form Require http server verification (httpsSmile | :) option, then Add and Close.

Installation Digital Certificate

Publish your web application on IIS, and run on localhost. After running, the control will appear on browser. Allow permission and install certificate, click on unknown publisher, then click on View certificate, click on Install certificate.

Output Image

Click on Next, then select option as per view, select Certification store "Trusted Root Certification Authorities", then OK.

Output Image

Follow Next with default option, then a message box will appear, click on Yes and finally success message will show, then OK.

Output Image

View Installed Digital Certificate

Open IE browser, then Tools menu-->Internet Options--->Content tab-->click on Certificates button, then select tab of "Trusted Root Certification Authorities", scroll certificate and select our certificate, then double click and View certificate.

Output Image

View Installed Control in Manage Add-ons

Open IE browser, then Tools menu-->Internet Options--->Program tab-->click on Manage Add-ons--->select All add-ons in dropdown box, then view our control and double click to view more information.

Output Image

Uninstall ActiveX control

Output Image

Conclusion

We covered the following topics: how to call Word/Excel application in ASP.NET web, how to create an ActiveX control, how to register a control, how to create a setup of control for COM, how to create a .cab file, how to create a Digital Certificate, how to sign a control, how to publish a control, how to install a Digital Certificate, how to set IE ActiveX control settings, View certificate, and check manage add-ons.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

R S Dodiya
Software Developer (Senior)
India India

Comments and Discussions

 
QuestionI am getting an error when compiling downloaded project. Any hints? [modified] PinmemberMr. Javaman18-Oct-12 9:05 
AnswerRe: I am getting an error when compiling downloaded project. Any hints? Pinmemberarevant29-Oct-12 20:09 
GeneralRe: I am getting an error when compiling downloaded project. Any hints? PinmemberR S Dodiya30-Oct-12 2:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140821.2 | Last Updated 15 Jun 2012
Article Copyright 2012 by R S Dodiya
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid