I am using MonthCalendar controls on a form to capture a "from" and "to" date range.
When a date is selected from the calendar control, the selected date is shown in a text box underneath.
Single-click on any of the dates and they correctly appear in the text box, except (in the supplied MRE) the maximum date (30th April 2022). I find I have to click the "30" twice on the calendar (not double-click) in order to have the date appear in the text box.
Hoping there is a reason and simple cure?
Below is the code for a minimum reproducible example (PS Version is 5.1.19041.4648):
# MAIN FORM
Add-Type -AssemblyName System.Windows.Forms
$Form = [system.Windows.Forms.Form] @{
Text = "CAL FOR SO"
Width = 255
Height = 240
StartPosition = "CenterScreen"
}
# START DATE CALENDAR CONTROL
$fromCAL = [System.Windows.Forms.MonthCalendar] @{
Location = "5,5"
MaxSelectionCount = 1
ShowToday = $False
ShowTodayCircle = $False
MinDate = Get-Date "01/04/2022"
MaxDate = Get-Date "30/04/2022"
}
$fromCAL.Add_DateSelected({
$fromBOX.Text = Get-Date $fromCAL.SelectionRange.start -f "dd/MM/yyyy"
})
$Form.Controls.Add($fromCAL)
# START DATE BOX
$fromBOX = [System.Windows.Forms.TextBox] @{
Location = "5,174"
Size = "225,40"
text = ""
}
$Form.Controls.Add($fromBOX)
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form.ShowDialog()
>Solution :
You seem to have hit a bug in .NET Framework that therefore affects Windows PowerShell, which has since been fixed in .NET (Core) and therefore also in PowerShell (Core) 7.
The workaround – which is also the better approach in general – is to subscribe to the DateChanged rather than the DateSelected event: the latter only fires in response to mouse clicks, whereas the former fires in response to a date change by any method (mouse click, keyboard, programmatic change).