C#编写activeX控件与js相互调用

来源:互联网 发布:网络设计师工资 编辑:程序博客网 时间:2024/05/21 07:15

控件代码(项目->生成:勾选为COM互操作注册):

    [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);    }public delegate void MessageHander(string msg);    [ComVisible(true)]//这个不能少    [Guid("C37124B1-8013-44C1-B8B4-9672B2AA175F")]    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]    public interface IActiveXEvents    {        [DispId(0x60020000)]        void PlayGame(string msg);//提供给javascript绑定    }[ComVisible(true)]    [Guid("FCB41AEE-C75C-4FFA-89E7-A53E6F6F8365")]    [ClassInterface(ClassInterfaceType.None)]    [ProgId("TransFileClientLib.TransFileCtrl")]    [ComSourceInterfaces(typeof(IActiveXEvents))]    public partial class TransFileCtrl : UserControl, IObjectSafety    {        public event MessageHander PlayGame;   #region IObjectSafety Members        public int GetInterfaceSafetyOptions(ref Guid riid, ref int pdwSupportedOptions, ref int pdwEnabledOptions)        {            pdwSupportedOptions = 1;            pdwEnabledOptions = 2;            return 0;        }        public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions)        {            return 0;        }        #endregion private void btnInvokeJs_Click(object sender, EventArgs e)        {            if (this.PlayGame != null)            {                PlayGame("成功!");            }            else            {                WinUtils.FailMsg("调用失败!");            }        }public void SayHello(){    MessageBox.show("hello!");}
前台代码:

<head><script type="text/javascript">    window.onload = function () {        var transFileCtrl = document.getElementById("transFileCtrl");        transFileCtrl.SayHello();    }    window.onbeforeunload = function () {        //alert("close");    }</script><script type="text/javascript" for="transFileCtrl" event="PlayGame(msg)">alert(msg);</script></head><body><object id="transFileCtrl" width="390" height="374"         classid="clsid:FCB41AEE-C75C-4FFA-89E7-A53E6F6F8365"         VIEWASTEXT style="font-size:9pt;width:387px;height:384px;"></object></body>



原创粉丝点击