■ 달력을 만드는 방법을 보여준다.
▶ CalendarInformation.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
using System; using System.Collections.Generic; namespace TestProject { /// <summary> /// 달력 정보 /// </summary> public class CalendarInformation { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 월별 일 수 배열 /// </summary> private static int[] _monthDayCountArray = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 연도 /// </summary> private int year = 0; /// <summary> /// 월 /// </summary> private int month = 0; /// <summary> /// 항목 리스트 /// </summary> private List<CalendarItem> itemList = new List<CalendarItem>(); /// <summary> /// 항목 딕셔너리 /// </summary> private Dictionary<DateTime, CalendarItem> itemDictionary = new Dictionary<DateTime, CalendarItem>(); /// <summary> /// 행 수 /// </summary> private int rowCount = 0; /// <summary> /// 컬럼 수 /// </summary> private int columnCount = 0; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 연도 - Year /// <summary> /// 연도 /// </summary> public int Year { get { return this.year; } set { this.year = value; } } #endregion #region 월 - Month /// <summary> /// 월 /// </summary> public int Month { get { return this.month; } set { this.month = value; } } #endregion #region 항목 리스트 - ItemList /// <summary> /// 항목 리스트 /// </summary> public List<CalendarItem> ItemList { get { return this.itemList; } } #endregion #region 항목 딕셔너리 - ItemDictionary /// <summary> /// 항목 딕셔너리 /// </summary> public Dictionary<DateTime, CalendarItem> ItemDictionary { get { return this.itemDictionary; } } #endregion #region 행 수 - RowCount /// <summary> /// 행 수 /// </summary> public int RowCount { get { return this.rowCount; } } #endregion #region 컬럼 수 - ColumnCount /// <summary> /// 컬럼 수 /// </summary> public int ColumnCount { get { return this.columnCount; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 계산하기 - Calculate() /// <summary> /// 계산하기 /// </summary> public void Calculate() { DateTime currentDate; this.itemList.Clear(); this.itemDictionary.Clear(); #region 마지막 일을 설정한다. int lastDay; if(this.month == 2 && DateTime.IsLeapYear(this.year)) { lastDay = 29; } else { lastDay = _monthDayCountArray[this.month - 1]; } #endregion #region 전체 일 수를 설정한다. int totalDayCount = 365 * (this.year - 1); for(int i = 1; i < this.year; i++) { if(DateTime.IsLeapYear(i)) { totalDayCount += 1; } } for(int i = 0; i < month - 1; i++) { totalDayCount += _monthDayCountArray[i]; } totalDayCount += 1; if(month >= 3 & DateTime.IsLeapYear(this.year)) { totalDayCount += 1; } #endregion #region 당월 항목을 추가한다. int start = totalDayCount % 7; for(int i = 0; i < lastDay; i++) { int sequence = start + i; CalendarItem calendarItem = new CalendarItem(); calendarItem.Date = new DateTime(year, month, i + 1); calendarItem.RowIndex = sequence / 7; calendarItem.ColumnIndex = sequence % 7; calendarItem.IsPreviousMonth = false; calendarItem.IsNexMonth = false; calendarItem.IsToday = (calendarItem.Date == DateTime.Now.Date); this.itemList.Add(calendarItem); this.itemDictionary.Add(calendarItem.Date, calendarItem); } #endregion #region 전월 항목을 추가한다. CalendarItem firstItem = this.itemList[0]; currentDate = firstItem.Date.AddDays(-1); for(int i = firstItem.ColumnIndex - 1; i > -1; i--) { CalendarItem calendarItem = new CalendarItem(); calendarItem.Date = currentDate; calendarItem.RowIndex = 0; calendarItem.ColumnIndex = i; calendarItem.IsPreviousMonth = true; calendarItem.IsNexMonth = false; calendarItem.IsToday = (calendarItem.Date == DateTime.Now.Date); this.itemList.Insert(0, calendarItem); this.itemDictionary.Add(calendarItem.Date, calendarItem); currentDate = currentDate.AddDays(-1); } #endregion #region 익월 항목을 설정한다. CalendarItem lastItem = this.itemList[this.itemList.Count - 1]; currentDate = lastItem.Date.AddDays(1); for(int i = lastItem.ColumnIndex + 1; i < 7; i++) { CalendarItem calendarItem = new CalendarItem(); calendarItem.Date = currentDate; calendarItem.RowIndex = lastItem.RowIndex; calendarItem.ColumnIndex = i; calendarItem.IsPreviousMonth = false; calendarItem.IsNexMonth = true; calendarItem.IsToday = (calendarItem.Date == DateTime.Now.Date); this.itemList.Add(calendarItem); this.itemDictionary.Add(calendarItem.Date, calendarItem); currentDate = currentDate.AddDays(1); } #endregion this.rowCount = this.itemList[this.itemList.Count - 1].RowIndex + 1; this.columnCount = 7; } #endregion } } |
▶ CalendarControl.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 |
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using System.Globalization; using System.Reflection; using System.Text; using System.Windows.Forms; namespace TestProject { /// <summary> /// 달력 컨트롤 /// </summary> public partial class CalendarControl : UserControl { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 컨트롤 마진 /// </summary> private const int CONTROL_MARGIN = 3; /// <summary> /// 헤더 높이 /// </summary> private const int HEADER_HEIGHT = 25; /// <summary> /// 달력 정보 /// </summary> private CalendarInformation calendarInformation = null; /// <summary> /// 요일 딕셔너리 /// </summary> private Dictionary<int, WeekdayItem> weekdayDictionary = new Dictionary<int, WeekdayItem>(); /// <summary> /// 일 딕셔너리 /// </summary> private Dictionary<CalendarItem, DayItem> dayDictionary = new Dictionary<CalendarItem, DayItem>(); /// <summary> /// 요일 제목 폰트 /// </summary> private Font weekdayTitleFont; /// <summary> /// 일 제목 당월 폰트 /// </summary> private Font dayTitleCurrentMonthFont; /// <summary> /// 일 제목 비당월 폰트 /// </summary> private Font dayTitleNonCurrentMonthFont; /// <summary> /// 일 제목 당일 폰트 /// </summary> private Font dayTitleTodayFont; /// <summary> /// 내용 폰트 /// </summary> private Font contentFont; /// <summary> /// 요일 제목 문자열 포맷 /// </summary> private StringFormat weekdayTitleStringFormat; /// <summary> /// 내용 문자열 포맷 /// </summary> private StringFormat contentStringFormat; /// <summary> /// 요일명 배열 /// </summary> private string[] dayNameArray; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 달력 정보 - CalendarInformation /// <summary> /// 달력 정보 /// </summary> public CalendarInformation CalendarInformation { get { return this.calendarInformation; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - CalendarControl() /// <summary> /// 생성자 /// </summary> public CalendarControl() { SetDoubleBuffered(this, true); InitializeComponent(); this.weekdayTitleFont = new Font("나눔고딕코딩", 12f); this.dayTitleCurrentMonthFont = new Font("나눔고딕코딩", 12f, FontStyle.Bold); this.dayTitleNonCurrentMonthFont = new Font("나눔고딕코딩", 12f); this.dayTitleTodayFont = new Font("나눔고딕코딩", 16f, FontStyle.Bold); this.contentFont = new Font("나눔고딕코딩", 12f); this.weekdayTitleStringFormat = new StringFormat(); this.weekdayTitleStringFormat.Alignment = StringAlignment.Center; this.weekdayTitleStringFormat.LineAlignment = StringAlignment.Center; this.contentStringFormat = new StringFormat(); this.contentStringFormat.Alignment = StringAlignment.Near; this.contentStringFormat.LineAlignment = StringAlignment.Center; this.dayNameArray = DateTimeFormatInfo.CurrentInfo.DayNames; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 달력 정보 설정하기 - SetCalendarInformation(calendarInformation) /// <summary> /// 달력 정보 설정하기 /// </summary> /// <param name="calendarInformation">연도</param> public void SetCalendarInformation(CalendarInformation calendarInformation) { this.calendarInformation = calendarInformation; Calculate(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 크기 변경시 처리하기 - OnSizeChanged(e) /// <summary> /// 크기 변경시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); Calculate(); } #endregion #region 페인트시 처리하기 - OnPaint(e) /// <summary> /// 페인트시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics graphics = e.Graphics; #region 그래픽스 객체 속성을 설정한다. graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; #endregion #region 컨트롤 배경을 칠한다. graphics.Clear(Color.White); #endregion #region 컨트롤 테두리 선을 그린다. graphics.DrawRectangle(Pens.Black, 0, 0, Width, Height); #endregion #region 요일 제목을 그린다. foreach(KeyValuePair<int, WeekdayItem> keyValuePair in this.weekdayDictionary) { int weekDay = keyValuePair.Key; WeekdayItem weekDayItem = keyValuePair.Value; graphics.DrawString(weekDayItem.WeekdayTitle, this.weekdayTitleFont, Brushes.Black, weekDayItem.Rectangle, this.weekdayTitleStringFormat); } #endregion foreach(KeyValuePair<CalendarItem, DayItem> keyValuePair in this.dayDictionary) { CalendarItem calendarItem = keyValuePair.Key; DayItem dayItem = keyValuePair.Value; graphics.SetClip(dayItem.Rectangle); #region 셀 배경을 칠한다. graphics.FillRectangle(dayItem.BackgroundBrush, dayItem.Rectangle); #endregion #region 셀 테두리 선을 그린다. graphics.DrawRectangle(dayItem.BorderPen , dayItem.Rectangle); #endregion #region 일 제목을 그린다. graphics.DrawString(dayItem.DayTitle, dayItem.DayTitleFont, Brushes.Black, dayItem.X + CONTROL_MARGIN, dayItem.Y + CONTROL_MARGIN); #endregion for(int i = 0; i < calendarItem.ContentList.Count; i++) { string content = calendarItem.ContentList[i]; graphics.DrawString(content, this.contentFont, Brushes.Black, dayItem.X + CONTROL_MARGIN, dayItem.Y + CONTROL_MARGIN + HEADER_HEIGHT + i * 20); } graphics.ResetClip(); } } #endregion #region 마우스 더블 클릭시 처리하기 - OnMouseDoubleClick(e) /// <summary> /// 마우스 더블 클릭시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnMouseDoubleClick(MouseEventArgs e) { base.OnMouseDoubleClick(e); foreach(KeyValuePair<CalendarItem, DayItem> keyValuePair in this.dayDictionary) { CalendarItem calendarItem = keyValuePair.Key; DayItem dayItem = keyValuePair.Value; if(dayItem.Rectangle.Contains(e.Location)) { StringBuilder stringBuilder = new StringBuilder(); for(int i = 0; i < calendarItem.ContentList.Count; i++) { stringBuilder.AppendLine(calendarItem.ContentList[i]); } InputContentPopupForm popupForm = new InputContentPopupForm(); popupForm.DateLabel = calendarItem.Date.ToString("yyyy-MM-dd"); popupForm.Content = stringBuilder.ToString().Trim(); if(popupForm.ShowDialog(this) == DialogResult.OK) { string[] contentArray = popupForm.Content.Split('\n'); calendarItem.ContentList.Clear(); foreach(string content in contentArray) { if(!string.IsNullOrEmpty(content)) { calendarItem.ContentList.Add(content); } } Invalidate(); } } } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 더블 버퍼링 설정하기 - SetDoubleBuffered(control, doubleBuffered) /// <summary> /// 더블 버퍼링 설정하기 /// </summary> /// <param name="control">컨트롤</param> /// <param name="doubleBuffered">더블 버퍼링 여부</param> private void SetDoubleBuffered(Control control, bool doubleBuffered = true) { PropertyInfo propertyInfo = typeof(Control).GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic); propertyInfo.SetValue(control, doubleBuffered, null); } #endregion #region 계산하기 - Calculate() /// <summary> /// 계산하기 /// </summary> private void Calculate() { this.weekdayDictionary.Clear(); this.dayDictionary.Clear(); if(Width == 0 || Height == 0) { return; } if(this.calendarInformation == null) { return; } int rowCount = this.calendarInformation.RowCount; int columnCount = this.calendarInformation.ColumnCount; int rowHeight = (int)((double)(Height - CONTROL_MARGIN - HEADER_HEIGHT) / rowCount ); int columnWidth = (int)((double)(Width - CONTROL_MARGIN ) / columnCount); for(int i = 0; i < 7; i++) { WeekdayItem item = new WeekdayItem(); item.X = i * columnWidth + CONTROL_MARGIN; item.Y = CONTROL_MARGIN; item.Width = columnWidth - CONTROL_MARGIN; item.Height = HEADER_HEIGHT; item.Rectangle = new Rectangle(item.X, item.Y, item.Width, item.Height); if(columnWidth > 60) { item.WeekdayTitle = this.dayNameArray[i]; } else { item.WeekdayTitle = this.dayNameArray[i].Replace("요일", string.Empty); } this.weekdayDictionary.Add(i, item); } foreach(CalendarItem calendarItem in this.calendarInformation.ItemList) { DayItem cellItem = new DayItem(); cellItem.X = calendarItem.ColumnIndex * columnWidth + CONTROL_MARGIN; cellItem.Y = calendarItem.RowIndex * rowHeight + CONTROL_MARGIN + HEADER_HEIGHT; cellItem.Width = columnWidth - CONTROL_MARGIN; cellItem.Height = rowHeight - CONTROL_MARGIN; cellItem.Rectangle = new Rectangle(cellItem.X, cellItem.Y, cellItem.Width, cellItem.Height); if(calendarItem.IsPreviousMonth || calendarItem.IsNexMonth) { cellItem.BackgroundBrush = Brushes.WhiteSmoke; cellItem.BorderPen = Pens.DarkGray; cellItem.DayTitleFont = this.dayTitleNonCurrentMonthFont; if(columnWidth > 60) { cellItem.DayTitle = string.Format("{0}/{1}", calendarItem.Date.Month, calendarItem.Date.Day); } else { cellItem.DayTitle = calendarItem.Date.Day.ToString(); } } else { if(calendarItem.IsToday) { if(calendarItem.ColumnIndex == 0 || calendarItem.ColumnIndex == 6) { cellItem.BackgroundBrush = Brushes.LavenderBlush; cellItem.BorderPen = new Pen(Brushes.DarkGray, 4f); } else { cellItem.BackgroundBrush = Brushes.White; cellItem.BorderPen = new Pen(Brushes.DarkGray, 4f); } } else { if(calendarItem.ColumnIndex == 0 || calendarItem.ColumnIndex == 6) { cellItem.BackgroundBrush = Brushes.LavenderBlush; cellItem.BorderPen = Pens.DarkGray; } else { cellItem.BackgroundBrush = Brushes.White; cellItem.BorderPen = Pens.DarkGray; } } if(calendarItem.IsToday) { cellItem.DayTitleFont = this.dayTitleTodayFont; cellItem.DayTitle = calendarItem.Date.Day.ToString(); } else { cellItem.DayTitleFont = this.dayTitleCurrentMonthFont; cellItem.DayTitle = calendarItem.Date.Day.ToString(); } } this.dayDictionary.Add(calendarItem, cellItem); } Invalidate(); } #endregion } } |
▶ MainForm.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using System; using System.Windows.Forms; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : Form { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); DateTime currentDate = DateTime.Now; CalendarInformation calendarInformation = new CalendarInformation(); calendarInformation.Year = currentDate.Year; calendarInformation.Month = currentDate.Month; calendarInformation.Calculate(); //calendarInformation.ItemDictionary[currentDate.Date].ContentList.Add("테스트"); this.calendarControl.SetCalendarInformation(calendarInformation); } #endregion } } |