WinForm与脚本的交互

 这是去年学习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();

}

 

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

 

2JS脚本中响应控件事件

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://chs.gotdotnet.com/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   


来源:http://www.cnblogs.com/sniper/archive/2004/08/09/31339.aspx





更多参考:http://msdn.microsoft.com/msdnmag/issues/02/01/UserCtrl/default.aspx
http://support.microsoft.com/?kbid=313891

posted @ 2007-05-18 13:52  M'  阅读(648)  评论(1编辑  收藏  举报