WinForm与脚本的交互
??? 將Winform Control嵌入IE,很多時候需要JS腳本與Control進行交互。一方面是在腳本中使用控件的屬性,調用控件的方法,另外一方面是腳本中能夠響應控件的事件。對于第一個問題較為簡單,我們還可以在腳本中使用控件屬性的值,也可以給屬性賦值,也可以調用控件的方法。
?<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
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://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??? ???
轉載于:https://www.cnblogs.com/Sniper/archive/2004/08/09/31339.html
總結
以上是生活随笔為你收集整理的WinForm与脚本的交互的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件设计原则
- 下一篇: 水晶报表-控制结构-For 循环(Cry