用IronPython作为.Net的脚本语言。

周末看了关于IronPython的介绍,觉得用IronPython作为.Net的脚本语言还不错,今天试验了一下。
不可错过的MSDN TV —— IronPython: Python on the .NET Framework (上)


添加IronPython的引用,在按钮事件中调用py脚本。
        private PythonEngine engine;
        
private void button1_Click(object sender, EventArgs e)
        {
            
if (engine == null)
            {
                engine 
= new PythonEngine();
                engine.Globals[
"win"= this;
                System.IO.FileStream fs 
= new System.IO.FileStream("scripting-log.txt",
   System.IO.FileMode.Create);
                engine.SetStandardOutput(fs);
            }
            
try
            {
                engine.ExecuteFile(
"test.py");
            }
            
catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }          
        }
在test.py中可以用脚本修改主窗口属性,添加控件,添加鼠标事件等。
import clr
clr.AddReferenceByPartialName(
"System.Windows.Forms")
clr.AddReferenceByPartialName(
"System.Drawing")
clr.AddReferenceByPartialName(
"IronPython")

from System.Windows.Forms import *
from System.Drawing import *

win.Text
="中文"
win.MaximizeBox
=False
win.Opacity
=0.9
win.ShowIcon
=False
win.TopMost
=True
#win.WindowState=FormWindowState.Minimized
MessageBox.Show(win.WindowState.ToString())

def click(f, a):
    l 
= Label(Text = "Hello")
    l.Location 
= a.Location
    l.AutoSize 
= True
    l.ForeColor 
= Color.Red
    f.Controls.Add(l)

win.Click 
+= click

def buttonClick(f,a):
  MessageBox.Show(f.Text)

b
=Button(Text="按钮")
b.Click 
+= buttonClick
win.Controls.Add(b)

for i in win.Controls: i.Font = Font("Verdana"9)

源代码下载
原文地址:https://www.cnblogs.com/Pharaoh/p/470123.html