.NET OCX开发

本文主要介绍怎么在.NET环境下开发OCX控件,打包安装部署程序,以及怎么在页面上调用控件。


开发

1、新建一个类库,然后打开类库的属性,应用程序→程序集信息
这里写图片描述

2、编辑程序集信息,主要是要把底部的 使程序集COM可见 勾上,点确定保存程序集信息
这里写图片描述

3、在类库的属性面板上选择 生成,拉到底部把 为COM互操作注册 勾上
这里写图片描述

4、在.NET下面开发OCX需要实现IObjectSafety接口,接口名称以及下面的GetInterfaceSafetyOptions和SetInterfaceSafetyOptions不要动

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    [Guid("84D0FC9A-DAB8-4620-B687-B3F9C950F2C8")]
    [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
    interface IObjectSafety
    {
        void GetInterfaceSafetyOptions(ref Guid riid, out  int pdwSupportdOptions, out int pdwEnabledOptions);

        void SetInterfaceSafetyOptions(ref Guid riid, int dwOptionsSetMask, int dwEnabledOptions);
    }
}

5、输出class实现IObjectSafety后,它里面的方法就可以在页面上使用了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Test
{
    [Guid("A79BF51F-D2E5-443A-BE7E-E7138FMEEFFB")]
    public class TestOCXMain : IObjectSafety
    {
        public void GetInterfaceSafetyOptions(ref Guid riid, out  int pdwSupportdOptions, out int pdwEnabledOptions)
        {
            pdwEnabledOptions = 2;
            pdwSupportdOptions = 1;
        }
        public void SetInterfaceSafetyOptions(ref Guid riid, int dwOptionsSetMask, int dwEnabledOptions)
        {
        }

        /// <summary>
        /// 页面调用方法,执行代码
        /// </summary>
        /// <param name="str"></param>
        public void Main(string str)
        {
            MessageBox.Show("你传给我的str : " + str);
        }
    }
}

打包

把程序打包成一个安装文件,在需要使用控件的客户端安装控件,就可以使用控件的功能了。

1、在解决方案下面添加一个安装部署项目,如图(因为我的VS2013没有安装这个东东,所以就只能用VS2010顶替一下)
这里写图片描述

2、选中项目,右键→添加 项目输出→选择输出主项目,确定
这里写图片描述

3、生成项目,在项目文件夹下面的Debug文件夹下面的.msi文件就是安装文件了。


使用

双击.msi文件,一直跑完就好。
页面上调用控件的方法:根据我们在程序中给定的GUID,在页面上添加<OBJECT id="TestOCX" classid="clsid:A79BF51F-D2E5-443A-BE7E-E7138FMEEFFB" style="width:0px;height:0px;display:none"></OBJECT>,然后js获取这个对象就可以直接调用它的方法了。
这里写图片描述

如果调用的时候,提示对象属性不存在,或者其他的,需要添加可信站点,并且需要启用OCX控件。

猜你喜欢

转载自blog.csdn.net/u012835032/article/details/80020383
今日推荐