ツールボックスのWindowsフォームにあるTimerの設定方法
デザイナ画面でGUIの作成を行う場合に、WindowsフォームデザイナーのツールボックスにあるTimerをどのように設定したらよいか不明だったので、調べたことをまとめておく。
SharpDevelopを使った場合の具体的な操作を記述するが、同じ操作はVisual Studioにも適用できる。
Timerを使って現在時刻を表示する時計のようなものを作成する。初めに基本的な画面のデザインを行う。ここでは、LabelとButtonを一つずつ配置する。
今は何もテキストを表示していないが、Labelの方に時刻を表示する。フォントの大きさを適当に変える。ボタンのラベルはStartとした。このボタンを押すことでLabelに時刻を表示し、1秒ごとに更新する。この更新の操作にTimerを使う。
Windowsフォームツールボックスの一番下にTimerがあるので、これをデザイナー画面のGUIにドラッグする。
黄色の領域の表示されたtimer1のアイコンをクリックして、プロパティを編集する。ここでは1秒ごとに時刻の表示を更新したいので、Intervalを1000(単位はms)とする。ボタンを押したときにタイマーが開始されるようにするため、EnabledはFalseのままとする。
次に、デザイナー画面でTimerアイコンをダブルクリックして、空のTickイベントハンドラを追加する。追加されたイベントハンドラで、現在時刻を求めてLabelにその時刻を表示する処理を記述する。その部分のコードは以下の通り。
def Timer1Tick(self, sender, e): d = datetime.datetime.today() stime = "%s:%s:%s" % (d.hour, d.minute, d.second) self._label1.Text = stime
加えて、ボタンを押したときにタイマーを開始するように、イベントハンドラに記述する。
def Button1Click(self, sender, e): self._timer1.Start()
以上で動くようになった。実行例は以下の通り。
全体のコードは以下の通り。
import datetime import System.Drawing import System.Drawing.Printing import System.Windows.Forms from System.Drawing import * from System.Drawing.Printing import * from System.Windows.Forms import * class MainForm(Form): def __init__(self): self.InitializeComponent() def InitializeComponent(self): self._components = System.ComponentModel.Container() self._label1 = System.Windows.Forms.Label() self._button1 = System.Windows.Forms.Button() self._timer1 = System.Windows.Forms.Timer(self._components) self.SuspendLayout() # # label1 # self._label1.Font = System.Drawing.Font("メイリオ", 20.25, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 128) self._label1.Location = System.Drawing.Point(71, 26) self._label1.Name = "label1" self._label1.Size = System.Drawing.Size(151, 36) self._label1.TabIndex = 1 # # button1 # self._button1.Font = System.Drawing.Font("メイリオ", 9, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 128) self._button1.Location = System.Drawing.Point(51, 78) self._button1.Name = "button1" self._button1.Size = System.Drawing.Size(180, 45) self._button1.TabIndex = 2 self._button1.Text = "Start" self._button1.UseVisualStyleBackColor = True self._button1.Click += self.Button1Click # # timer1 # self._timer1.Interval = 1000 self._timer1.Tick += self.Timer1Tick # # MainForm # self.ClientSize = System.Drawing.Size(283, 151) self.Controls.Add(self._button1) self.Controls.Add(self._label1) self.Name = "MainForm" self.Text = "Test" self.ResumeLayout(False) def Button1Click(self, sender, e): self._timer1.Start() def Timer1Tick(self, sender, e): d = datetime.datetime.today() stime = "%s:%s:%s" % (d.hour, d.minute, d.second) self._label1.Text = stime