C#: Finding Hours/Minutes from a Click Position
This took a while to get working, but I got there eventually. It's used in OnTime to calculate the number of hours and minutes a user has clicked on. I have rows of horizontal lines which show hours. It's easy to extract a time from a click position, but generally people don't need that much precision and unless the grid is quite large (bigger than 1440 pixels), you won't have 1px per minute anyway.
This snippet will find the nearsest 30 minute interval, so if a user clicks ⅓ of the way between the 4th and 5th division, this would round to 4 hours and 30 minutes.
double clickPosition = ((double)e.Y + -this.AutoScrollPosition.Y) / heightPerHour; int hours = (int)clickPosition; int mins = (int)((clickPosition - (double)hours) * 60); int roundedMinutes = (int)Math.Round((double)mins / 30, 0) * 30; double fractionalHours = hours + (double)(roundedMinutes / 60.0);
This is designed for a control which autoscrolls, so the actual position of the click is determined first. heightPerHour is the height of each row (each hour).

Comments
Leave a Comment