2つ目の画面を表示する

MessageBoxで表示されるメッセージダイアログでは、簡単なメッセージを示せるのみである。いろいろなガジェットを配置できる正式な画面をもう一つ表示したい場合にはどうすればいいか?

現在、開発環境としてはSharpDevelopを使ってGUIの画面をデザインしている。2つ目の画面のデザインも同じくSharpDevelopを使う。そのためには、まずSolutionにファイルを追加する。
最初の画面はMainForm.pyで定義されている。2つ目の画面を定義するファイルForm1.pyを追加する。Form1.pyの中に新しく開く画面の内容を記述する。これらのファイル名は自動で決められたもの。

まずメイン画面の内容(MainForm.py)は以下の通り。

import System.Drawing
import System.Windows.Forms

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

import Form1

class MainForm(Form):
 def __init__(self):
  self.InitializeComponent()
 
 def InitializeComponent(self):
  self._button1 = System.Windows.Forms.Button()
  self.SuspendLayout()
  #
  # button1
  #
  self._button1.Location = System.Drawing.Point(54, 53)
  self._button1.Name = "button1"
  self._button1.Size = System.Drawing.Size(170, 70)
  self._button1.TabIndex = 0
  self._button1.Text = "Open new window"
  self._button1.UseVisualStyleBackColor = True
  self._button1.Click += self.Button1Click
  #
  # MainForm
  #
  self.ClientSize = System.Drawing.Size(283, 174)
  self.Controls.Add(self._button1)
  self.Name = "MainForm"
  self.Text = "Sample"
  self.ResumeLayout(False)


 def Button1Click(self, sender, e):
  newwin = Form1.Form1()
  newwin.Show()       #モードレスで表示する
#  newwin.ShowDialog() #またはモーダルで表示する

ボタンを押したときに開かれる2つ目の画面は以下の通り。ここでは文字を表示するだけの簡単な画面だけれど...。

import System.Drawing
import System.Windows.Forms

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

class Form1(Form):
 def __init__(self):
  self.InitializeComponent()
 
 def InitializeComponent(self):
  self._label1 = System.Windows.Forms.Label()
  self.SuspendLayout()
  #
  # label1
  #
  self._label1.Font = System.Drawing.Font("MS ゴシック", 18, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 128)
  self._label1.Location = System.Drawing.Point(35, 102)
  self._label1.Name = "label1"
  self._label1.Size = System.Drawing.Size(214, 57)
  self._label1.TabIndex = 0
  self._label1.Text = "This is new form."
  #
  # Form1
  #
  self.ClientSize = System.Drawing.Size(284, 262)
  self.Controls.Add(self._label1)
  self.Name = "Form1"
  self.Text = "Form1"
  self.ResumeLayout(False)

動かす際には以下のコードを実行する。

import clr
clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')

from System.Windows.Forms import Application
import MainForm

Application.EnableVisualStyles()
form = MainForm.MainForm()
Application.Run(form)


▲メイン画面のボタンを押す

▲2つ目の画面が開く