使用C#开发ActiveX控件

来源:互联网 发布:淘宝怎么删除收获地址 编辑:程序博客网 时间:2024/04/29 16:02

ActiveX 是一个开放的集成平台,为开发人员、用户和 Web生产商提供了一个快速而简便的在 Internet 和 Intranet 创建程序集成和内容的方法。 使用 ActiveX, 可轻松方便的在 Web页中插入 多媒体效果、 交互式对象、以及复杂程序,创建用户体验相当的高质量多媒体 CD-ROM 。

     简单的说,用activeX和js差不多,但是有些是js无法实现的,这个时候就可以考虑一下activeX,一般要求是在客户端执行的程序,比如对本机的串口操作等,下面来简单介绍下如何用C#自己开发一个activeX组件,并在web中应用

 

 更改“项目属性-应用程序-程序集信息”设置,勾选“使程序集 COM 可见”:

 

 更改“项目属性-生成”设置,勾选“为 COM 互操作 注册

 

 修改AssemblyInfo.cs文件,添加[assembly: AllowPartiallyTrustedCallers()]项(需要引用System.Security名称空间): 

using System.Runtime.InteropServices;

using System.Security;

// 有关程序集的常规信息通过下列属性集

// 控制。更改这些属性值可修改

// 与程序集关联的信息。

[assemblyAssemblyTitle("ActivexDemo")]

[assemblyAssemblyDescription("")]

[assemblyAssemblyConfiguration("")]

[assemblyAssemblyCompany("微软中国")]

[assemblyAssemblyProduct("ActivexDemo")]

[assemblyAssemblyCopyright("Copyright © 微软中国 2012")]

[assemblyAssemblyTrademark("")]

[assemblyAssemblyCulture("")]

 

// 将 ComVisible 设置为 false 使此程序集中的类型

// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,

// 则将该类型上的 ComVisible 属性设置为 true。

[assemblyComVisible(true)]

 

// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID

[assemblyGuid("f5438267-5c1e-4c24-b2e0-c2f172e753a4")]

 

// 程序集的版本信息由下面四个值组成:

//

//     主版本

//      次版本

//      内部版本号

//      修订号

//

// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,

// 方法是按如下所示使用“*”:

// [assembly: AssemblyVersion("1.0.*")]

[assemblyAssemblyVersion("1.0.0.0")]

[assemblyAssemblyFileVersion("1.0.0.0")]

[assemblyAllowPartiallyTrustedCallers()]

 

 添加一个Windows用户控件:

 

完成控件开发后,为了使该用户控件作为一个ActiveX控件进行使用,还需要做以下修改:
      首先,为控件类添加GUID,这个编号将用于B/S系统的客户端调用时使用(可以使用 工具-创建GUID 菜单创建一个GUID): 

或者通过程序获得

MessageBox.Show(Guid.NewGuid().ToString());

为了提高程序的安全性,以便在客户端安装的时候在浏览器提高信任度,我们需要实现接口IObjectSafety

 

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ActivexDemo
{
    [ComImport, GuidAttribute("CB5BDC81-93C1-11CF-8F20-00805F2CD064")]
    [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IObjectSafety
    {
        [PreserveSig]
        int GetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] ref int pdwSupportedOptions, [MarshalAs(UnmanagedType.U4)] ref int pdwEnabledOptions);

        [PreserveSig()]
        int SetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] int dwOptionSetMask, [MarshalAs(UnmanagedType.U4)] int dwEnabledOptions);
    }

然后在代码中实现接口即可

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;//Guid引用
namespace ActivexDemo
{
   
    [Guid("0b6ed426-9e67-4cf3-99da-8a346a98e5c6")]
    public partial class Uc : UserControl,IObjectSafety
    {
        public Uc()
        {
            InitializeComponent();
        } 
        #region IObjectSafety 成员
        private const string _IID_IDispatch = "{00020400-0000-0000-C000-000000000046}";
        private const string _IID_IDispatchEx = "{a6ef9860-c720-11d0-9337-00a0c90dcaa9}";
        private const string _IID_IPersistStorage = "{0000010A-0000-0000-C000-000000000046}";
        private const string _IID_IPersistStream = "{00000109-0000-0000-C000-000000000046}";
        private const string _IID_IPersistPropertyBag = "{37D84F60-42CB-11CE-8135-00AA004BB851}";

        private const int INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001;
        private const int INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002;
        private const int S_OK = 0;
        private const int E_FAIL = unchecked((int)0x80004005);
        private const int E_NOINTERFACE = unchecked((int)0x80004002);

        private bool _fSafeForScripting = true;
        private bool _fSafeForInitializing = true;

        public int GetInterfaceSafetyOptions(ref Guid riid, ref int pdwSupportedOptions, ref int pdwEnabledOptions)
        {
            int Rslt = E_FAIL;

            string strGUID = riid.ToString("B");
            pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;
            switch (strGUID)
            {
                case _IID_IDispatch:
                case _IID_IDispatchEx:
                    Rslt = S_OK;
                    pdwEnabledOptions = 0;
                    if (_fSafeForScripting == true)
                        pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER;
                    break;
                case _IID_IPersistStorage:
                case _IID_IPersistStream:
                case _IID_IPersistPropertyBag:
                    Rslt = S_OK;
                    pdwEnabledOptions = 0;
                    if (_fSafeForInitializing == true)
                        pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_DATA;
                    break;
                default:
                    Rslt = E_NOINTERFACE;
                    break;
            }

            return Rslt;
        }

        public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions)
        {
            int Rslt = E_FAIL;
            string strGUID = riid.ToString("B");
            switch (strGUID)
            {
                case _IID_IDispatch:
                case _IID_IDispatchEx:
                    if (((dwEnabledOptions & dwOptionSetMask) == INTERFACESAFE_FOR_UNTRUSTED_CALLER) && (_fSafeForScripting == true))
                        Rslt = S_OK;
                    break;
                case _IID_IPersistStorage:
                case _IID_IPersistStream:
                case _IID_IPersistPropertyBag:
                    if (((dwEnabledOptions & dwOptionSetMask) == INTERFACESAFE_FOR_UNTRUSTED_DATA) && (_fSafeForInitializing == true))
                        Rslt = S_OK;
                    break;
                default:
                    Rslt = E_NOINTERFACE;
                    break;
            }

            return Rslt;
        }

        #endregion
    }
}

这样ActiveX的基本设置完成了,这个时候我们就可以利用ActiveX实现自己需要的功能了,我们两个举个例子

一、              在页面中放置一个文本框和一个按钮,当点击按钮的时候,把ActiveX中的值传到页面的文本框中

二、              在ActiveX的控件中放置一个按钮,当触发按钮事件后,把ActiveX的值传到页面的文本框中

上面这两个例子其实就是想实现如何实现js调用ActiveX和ActiveX调用页面的Js的,现在我们写一下代码,先看看第一种情况,在ActiveX中我们写了一个GetStr方法,用来返回一个值,然后把这个值传到页面中

   public string GetStr()

    {

            return "这是从ActiveX传过来的值";

}

好了,现在我们需要新建一个安装文件

复制代码
复制代码

1、   新建一个安装项目

 

 

2、 在项目上点右键,【添加】->【项目输出】,选择上边的项目

 

    

       

 

如果有多个项目,可以选择需要安装的项目就可以了

点击项目,按下“F4”,设置属性

 

    

 

3、  生成项目 
会生成两个文件,一个exe文件和一个msi文件

     

  

然后把这两个文件拷到项目的lib文件夹下面

1、  新建一个页面,添加下面的代码

    <object classid="clsid:0b6ed426-9e67-4cf3-99da-8a346a98e5c6" codebase="lib/setup.exe"

        width="200" height="40" id="helloBossma">

 </object>

     然后在页面中添加javascript代码,按钮和文本框

   

复制代码
<head runat="server">
    <title>无标题页</title>
    <script type="text/javascript">
       function passValue()
       {  
 document.getElementById("textValue").value=document.getElementById("helloBossma").GetStr();
       }
    </script>
</head>
<body>
    <object  classid="clsid:0b6ed426-9e67-4cf3-99da-8a346a98e5c6" codebase="lib/setup.exe"
        width
="200" height="40" id="helloBossma">
    </object>
    <form id="form1" runat="server">
    <div>
        <input id="textValue" type="text" />
        <input id="Button1" type="button" value="传值" onclick="passValue()"/>
    </div>
    </form>
</body>
</html>
复制代码

 

这个时候我们就可以打开浏览器浏览页面了

 

运行加载提示的加载项就可以了

  

这个时候我们点击按钮传值就可以把ActiveX中的值传过来了

 

 

接着看看如何用ActiveX调用Javascript

首先在ActiveX中写一个方法用来将页面的js函数传过来。

页面的js函数

     window.onload=function()

       {

          document.getElementById("helloBossma").regJs(window,"show");

       }

       function show(str)

       {

          document.getElementById("text1").value=str;

       }

ActiveX中我们需要添加引用

 

复制代码
using mshtml;

        private IHTMLWindow2 temphtml = null;
        private string functionstr = "";

        public void RegJs(object win, string fuc)
        {
            temphtml = (IHTMLWindow2)win;
            if (temphtml != null && !string.IsNullOrEmpty(fuc))
            {
                functionstr = fuc;
            }
            else
            {
                temphtml = null;
                functionstr = "";
                MessageBox.Show("注册脚本失败!");
            }
        }

在控件中放置一个按钮,触发按钮的onclick事件,在事件中将值传给页面的js,从而完成赋值

    private void button1_Click(object sender, EventArgs e)

        {

            temphtml.execScript(functionstr + "('从activeX中传值到页面')", "JScript");  

        }

原帖:http://www.cnblogs.com/shuang121/archive/2012/06/04/2534296.html

0 0
原创粉丝点击