2017年12月26日

【PowerShell】天気予報を取得してWindowsフォームに表示する


以前書いた、『Invoke-RestMethodを使って天気予報を取得してみる』の方法で取得した天気情報をWindowsフォームに表示するようにしてみました。

とりあえず明日の天気だけ表示するようにしています。今日とか明後日も表示させようか思いましたがラベルとか配置させるのが面倒なのでやめました。(笑)

#天気情報取得
$city = 140020
$tenki = Invoke-RestMethod http://weather.livedoor.com/forecast/webservice/json/v1?city=$city

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
 
#フォーム
$form = New-Object System.Windows.Forms.Form 
$form.Text = "天気予報"
$form.Size = New-Object System.Drawing.Size(200,180) 
$form.StartPosition = "CenterScreen"
$form.BackColor = [System.Drawing.Color]::White
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle

#タイトル
$title = New-Object System.Windows.Forms.Label
$title.Location = New-Object System.Drawing.Point(20, 20) 
$title.Size = New-Object System.Drawing.Size(200,20) 
$title.Text = $tenki.title
$title.Font = New-Object System.Drawing.Font($title.Font, [System.Drawing.FontStyle]::Bold)
$form.Controls.Add($title) 

#ラベル1
$label1 = New-Object System.Windows.Forms.Label
$label1.Location = New-Object System.Drawing.Point(30, 50) 
$label1.Size = New-Object System.Drawing.Size(200,20) 
$label1.Text = $tenki.forecasts[1].dateLabel + '  ' + ([DateTime]::Parse($tenki.forecasts[1].date)).ToString("yyyy年MM年dd日")
$form.Controls.Add($label1) 

#PictureBox
$pic = New-Object System.Windows.Forms.PictureBox
$pic.ImageLocation = $tenki.forecasts[1].image.url
$pic.Location = New-Object System.Drawing.Point(30, 80) 
$pic.Size = New-Object System.Drawing.Size(50, 31)
$pic.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::Zoom
$form.Controls.Add($pic) 

#予報
$telop = New-Object System.Windows.Forms.Label
$telop.Location = New-Object System.Drawing.Point(90, 80) 
$telop.Size = New-Object System.Drawing.Size(70,20) 
$telop.Text = $tenki.forecasts[1].telop
$form.Controls.Add($telop) 

#最高気温
$tempmax = New-Object System.Windows.Forms.Label
$tempmax.Location = New-Object System.Drawing.Point(90, 100) 
$tempmax.Size = New-Object System.Drawing.Size(30,20) 
$tempmax.Text = $tenki.forecasts[1].temperature.max.celsius
$tempmax.ForeColor = [System.Drawing.Color]::Red
$form.Controls.Add($tempmax) 

#最低気温
$tempmin = New-Object System.Windows.Forms.Label
$tempmin.Location = New-Object System.Drawing.Point(120, 100) 
$tempmin.Size = New-Object System.Drawing.Size(30,20) 
$tempmin.Text = $tenki.forecasts[1].temperature.min.celsius
$tempmin.ForeColor = [System.Drawing.Color]::Blue
$form.Controls.Add($tempmin) 

#フォームを表示
$result = $form.ShowDialog()

#リソースを開放
$pic.Image.Dispose()
$pic.Image = $null

実行結果








スポンサーリンク