Skip to content

Instantly share code, notes, and snippets.

@joshooaj
Last active October 1, 2024 20:48
Show Gist options
  • Save joshooaj/ea5776d8051e3922f13133bf0756dbd3 to your computer and use it in GitHub Desktop.
Save joshooaj/ea5776d8051e3922f13133bf0756dbd3 to your computer and use it in GitHub Desktop.
Simple datetime picker ui implementation for Windows PowerShell
function Show-DateTimePicker {
[CmdletBinding()]
param(
[Parameter()]
[string]
$Title = 'Show-DateTimePicker',
[Parameter()]
[DateTimeKind]
$Kind = [DateTimeKind]::Local
)
process {
try {
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
$datePicker = [System.Windows.Forms.DateTimePicker]@{
Location = [System.Drawing.Point]::new(10, 10)
}
$timePicker = [System.Windows.Forms.DateTimePicker]@{
Format = [System.Windows.Forms.DateTimePickerFormat]::Time
ShowUpDown = $true
Location = [System.Drawing.Point]::new(10, 35)
}
$okButton = [System.Windows.Forms.Button]@{
Location = [System.Drawing.Point]::new(135, 60)
Text = 'OK'
}
$okButton.add_Click({
param($sender, $e)
$sender.Parent.DialogResult = [System.Windows.Forms.DialogResult]::OK
$sender.Parent.Close()
})
$cancelButton = [System.Windows.Forms.Button]@{
Location = [System.Drawing.Point]::new(55, 60)
Text = 'Cancel'
}
$cancelButton.add_Click({
param($sender, $e)
$sender.Parent.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$sender.Parent.Close()
})
$form = [System.Windows.Forms.Form]@{
Text = $Title
AcceptButton = $okButton
CancelButton = $cancelButton
Size = [System.Drawing.Size]::new(240, 150)
}
$form.Controls.AddRange([System.Windows.Forms.Control[]]@($datePicker, $timePicker, $cancelButton, $okButton))
if ($form.ShowDialog() -ne [System.Windows.Forms.DialogResult]::OK) {
Write-Error "DateTime selection cancelled"
return
}
[datetime]::new(
$datePicker.Value.Year,
$datePicker.Value.Month,
$datePicker.Value.Day,
$timePicker.Value.Hour,
$timePicker.Value.Minute,
$timePicker.Value.Second,
$timePicker.Value.Millisecond,
$Kind)
#[datetime]::SpecifyKind($datetime, $Kind)
} finally {
$form.Dispose()
$timePicker.Dispose()
$datePicker.Dispose()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment