Python CLR WinForms – Opening another from from an existing form

Question:

I am having some extreme difficulty with something so simple. All I am trying to do is launch another Windows Form from an existing Windows Form in Python. I’ve tried everything I can think of and I cannot figure out. Below is a example program:

import clr

clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
clr.AddReference("System.ComponentModel")

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

class MyForm(Form):
    def __init__(self):
        self.StartPosition = FormStartPosition.CenterScreen

        self.btnTest = Button()
        self.btnTest.Name = 'btnTest'
        self.btnTest.Text = "Test"
        self.btnTest.Size = Size(80, 30)

        self.Controls.Add(self.btnTest)
        self.btnTest.Click += self.Add_Control_Limits_Form_Click

    def Add_Control_Limits_Form_Click(self, sender, args):
        Application.Run(MySecondForm())

class MySecondForm(Form):   
    def __init__(self2):
        self2.StartPosition = FormStartPosition.CenterScreen
        self2.AutoScaleMode = AutoScaleMode.Font
        self2.ClientSize = Size(800, 450)
        self2.Text = "Form2"

Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)

Application.Run(MyForm())

Which, when I run it, it gives me this error message:

InvalidOperationException : Starting a second message loop on a single thread is not a valid operation. Use Form.ShowDialog instead.

I don’t think it’s as simple as just putting MySecondForm.ShowDialog() since I have this as a class. What am I missing?

Asked By: EricALionsFan

||

Answers:

I figured it out.

So, within the button click event, add these lines of code:

    self.TopLevel = False
    YF = YourForm()
    YF.ShowDialog()
    self.TopLevel = True

…if you want it modal. I did.

You don’t need the Application.Run(MySecondForm()) code within the button click event.

Then, within your second form class, just initialize your form the way you want.

Answered By: EricALionsFan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.