using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace KssSmaPlaLib.Forms { public static class DatePickerHelper { public static DateTime? ShowDateDialog( DateTime? defaultDate = null, string title = "日付を選択してください") { // 1. その場限りのフォームを作成 using (Form form = new Form()) { DateTimePicker dtp = new DateTimePicker(); Button btnOk = new Button(); // フォームの設定 form.Text = title; form.Size = new System.Drawing.Size(240, 120); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.StartPosition = FormStartPosition.CenterParent; form.MaximizeBox = false; form.MinimizeBox = false; // DateTimePickerの設定 dtp.Location = new System.Drawing.Point(10, 10); dtp.Size = new System.Drawing.Size(200, 20); dtp.Format = DateTimePickerFormat.Short; // ★ ここで初期値をセット! // 引数がnullなら今日の値を、あればその値をセットします。 dtp.Value = defaultDate ?? DateTime.Today; // OKボタンの設定 btnOk.Text = "OK"; btnOk.DialogResult = DialogResult.OK; // これを押すとフォームが閉じる btnOk.Location = new System.Drawing.Point(135, 45); form.AcceptButton = btnOk; // EnterキーでOK // コントロールを追加 form.Controls.Add(dtp); form.Controls.Add(btnOk); // 2. ダイアログとして表示 if (form.ShowDialog() == DialogResult.OK) { return dtp.Value; // 選択された日付を返す } } return null; // キャンセルされた場合 } } }