C# 代码
我将以下C#代码编译到名为“ MinimalFormsApp.dll ”的库中
using System;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsTest
{
public static class CreateACoolWindow
{
public static void Main(string[] args)
{
CreateWindow();
}
public static void CreateWindow()
{
Thread winFormsThread = new Thread(new ThreadStart(StartFormApplication));
winFormsThread.SetApartmentState(ApartmentState.STA);
winFormsThread.Start();
Console.WriteLine("Started thread");
}
private static void StartFormApplication()
{
Application.EnableVisualStyles();
Console.WriteLine("EnableVisualStyles");
Application.SetCompatibleTextRenderingDefault(false);
Console.WriteLine("SetCompatibleTextRenderingDefault");
FormSubClass dmw = new FormSubClass();
Console.WriteLine("Created window object");
Application.Run(dmw);
}
}
public class FormSubClass : Form
{
public FormSubClass()
{
Console.WriteLine("FormSubClass Constructor called");
InitializeComponent();
}
private void InitializeComponent()
{
Console.WriteLine("Starting component init......");
this.SuspendLayout();
this.AutoScaleDimensions = new SizeF(6F, 13F);
this.AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new Size(300, 500);
this.Name = "FormSubClass";
this.Text = "FormSubClass";
this.ResumeLayout(false);
this.PerformLayout();
}
}
}
Python代码
使用Python for .NET和 Python 2.7 for x86 我尝试从这个 C# 库调用 CreateWindow() 方法。
我的python代码如下:
import clr
clr.AddReference("MinimalFormsApp")
from WindowsFormsTest import CreateACoolWindow
CreateACoolWindow.CreateWindow()
#Print some output
print "Mary had a little lamb,"
print "it's fleece was white as snow;"
print "and everywhere that Mary went",
print "her lamb was sure to go."
控制台输出
这是 Python 在控制台上打印的内容
启动线程
Mary 有一只小羊羔,EnableVisualStyles
SetCompatibleTextRenderingDefault它的羊毛像雪一样白;
玛丽所到之处,她的小羊一定会去。
FormSubClass 构造函数调用
可以看出,它没有打印“Starting component init......”,也没有打印“Created window object”,也没有实际创建Window。Python 程序结束并且不产生错误消息说明为什么没有创建窗口。
如果我从另一个 C# 程序调用相同的 C# 库,那么所有内容都会按预期打印并创建窗口。
有谁知道为什么 Python for .NET 在 Forms 构造函数上静默失败?