这是去年学习SmartClient时写下的,有兴趣可以看看
    将Winform Control嵌入IE,很多时候需要JS脚本与Control进行交互。一方面是在脚本中使用控件的属性,调用控件的方法,另外一方面是脚本中能够响应控件的事件。对于第一个问题较为简单,我们还可以在脚本中使用控件属性的值,也可以给属性赋值,也可以调用控件的方法。 
 

1、 脚本中传参数,使用控件的属性,调用控件方法

1)在控件Test_JsUseCtrl.cs中,添加textBox1,定义属性Str,如

private string str;
     public string Str
     { 
 
          get{return str;}
         set{     str = value;textBox1.Text = value;}
}

2)定义public方法用于显示textBox1内容如

public void ShowText()
     { 
 
          MessageBox.Show(textBox1.Text,"TextBox的内容”,MessageBoxButtons.OK,MessageBoxIcon.Information);
}

3)在页面添加TextBox,Button等,点击Button1可以将页面输入值赋给控件属性,点击Button2可以调用控件方法

function Button1_onclick() { 
Test_JsUseCtrl.Str = Text1.value; 
} 
function Button2_onclick() { 
Test_JsUseCtrl.ShowText(); 
}

上面部是点击或者触发页面控件事件来获得控件的属性和方法,下面部分就是控件通过事件来调用脚本中的方法,即在脚本中响应控件事件。

2、JS脚本中响应控件事件

1)在控件中添加接口ClickEvent

// Source interface for events to be exposed
     // Add GuidAttribute to the source interface to supply an explicit System.Guid.
     // Add InterfaceTypeAttribute to indicate that interface is the IDispatch interface.
     [System.Runtime.InteropServices.GuidAttribute("0422D916-C11A-474e-947D-45A107038D12") ]
     [System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIDispatch)]
     public interface ControlEvents 
         // Add a DisIdAttribute to any members in the source interface to         // specify the COM DispId.
     { 
 
          [System.Runtime.InteropServices.DispIdAttribute(0x60020000)]
         void ClickEvent(int x, int y);
     }

2、为控件添加属性    

// Add a ComSourceInterfaces attribute to the control to identify        //the list of interfaces that are exposed as COM event sources. 
     [System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None),System.Runtime.InteropServices.ComSourceInterfaces(typeof(ControlEvents))]
     public class MyWindowControl : System.Windows.Forms.UserControl //, ComInteropControlInterface

2、  在Button的Click事件中调用接口方法

if (ClickEvent != null) 
     { 
 
          ClickEvent(0, 0);
}

3、  在JS脚本中响应接口事件

function ctrl::ClickEvent(a,b) 
{ 
alert(String(a)+"+"+String(b)); 
}

脚本响应控件的事件稍微复杂 

注:如果弹出关于安全方面的提示,把IE->安全->信任站点s->自定义级别下的,“对没有标记为安全的ActiveX控件进行初始化和脚本运行”,设为启用。(上面的思路就是将Control作为ActiveX)

参考: 

http:///quickstart/winforms/doc/WinFormsIeSourcing.aspx

HOW TO: Sink Managed C# Events in Internet Explorer Script

PRB: Security Exception When You Use Event Handlers in Internet Explorer