ahhu
ahhu

Reputation: 5

How to Import a C# WinForms DLL File in Python

I want to use a GUI made with C# WinForms in Python.

Here are the versions I am using:

Python: 3.12 Pythonnet: 3.0.5 For C#, I used Visual Studio 2022. When creating the project, I selected "WinForms" and wrote the code as follows:

enter image description here

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("hello");

        }

        public static void ShowForm()
        {
            Application.Run(new Form1());
        }

    }
}

After building the solution in C#, I copied the DLL file from the Debug folder into the Python project folder.

For Python, I am using Visual Studio Code.

enter image description here

import clr
import os



def test():

    clr.AddReference(r"./WinFormsApp1.dll")


    from WinFormsApp1 import Form1


    Form1.ShowForm() 


if __name__ == "__main__":
    test()

from WinFormsApp1 import Form1

As shown in the image, this part is not recognized.

What should I do?

Upvotes: 0

Views: 88

Answers (0)

Related Questions