■ 메모장을 흉내내는 방법을 보여준다.
▶ AboutDialog.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 |
using System.Diagnostics; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; namespace TestProject { /// <summary> /// ABOUT 대화 상자 /// </summary> public class AboutDialog : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - AboutDialog(ownerWindow) /// <summary> /// 생성자 /// </summary> /// <param name="ownerWindow">오너 윈도우</param> public AboutDialog(Window ownerWindow) { Assembly assembly = Assembly.GetExecutingAssembly(); #region 제목 AssemblyTitleAttribute assemblyTitleAttribute = (AssemblyTitleAttribute)assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false)[0]; string title = assemblyTitleAttribute.Title; #endregion #region 버전 AssemblyFileVersionAttribute assemblyFileVersionAttribute = (AssemblyFileVersionAttribute)assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)[0]; string version = assemblyFileVersionAttribute.Version.Substring(0, 3); #endregion #region 저작권 AssemblyCopyrightAttribute assemblyCopyrightAttribute = (AssemblyCopyrightAttribute)assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false)[0]; string copyright = assemblyCopyrightAttribute.Copyright; #endregion Title = "About " + title; ShowInTaskbar = false; SizeToContent = SizeToContent.WidthAndHeight; ResizeMode = ResizeMode.NoResize; Left = ownerWindow.Left + 96d; Top = ownerWindow.Top + 96d; StackPanel mainStackPanel = new StackPanel(); Content = mainStackPanel; #region 제목 텍스트 블럭 TextBlock titleTextBlock = new TextBlock(); titleTextBlock.Text = title + " Version " + version; titleTextBlock.FontFamily = new FontFamily("Times New Roman"); titleTextBlock.FontSize = 32d; titleTextBlock.FontStyle = FontStyles.Italic; titleTextBlock.Margin = new Thickness(24d); titleTextBlock.HorizontalAlignment = HorizontalAlignment.Center; mainStackPanel.Children.Add(titleTextBlock); #endregion #region 저작권 텍스트 블럭 TextBlock copyrightTextBlock = new TextBlock(); copyrightTextBlock.Text = copyright; copyrightTextBlock.FontSize = 20; // 15 points. copyrightTextBlock.HorizontalAlignment = HorizontalAlignment.Center; mainStackPanel.Children.Add(copyrightTextBlock); #endregion #region 웹사이트 텍스트 블럭 Run webSiteRun = new Run("www.charlespetzold.com"); Hyperlink webSiteHyperlink = new Hyperlink(webSiteRun); webSiteHyperlink.Click += webSiteHyperlink_Click; TextBlock webSiteTextBlock = new TextBlock(webSiteHyperlink); webSiteTextBlock.FontSize = 20; webSiteTextBlock.HorizontalAlignment = HorizontalAlignment.Center; mainStackPanel.Children.Add(webSiteTextBlock); #endregion #region OK 버튼 Button okButton = new Button(); okButton.Content = "OK"; okButton.IsDefault = true; okButton.IsCancel = true; okButton.HorizontalAlignment = HorizontalAlignment.Center; okButton.MinWidth = 48d; okButton.Margin = new Thickness(24d); okButton.Click += okButton_Click; mainStackPanel.Children.Add(okButton); okButton.Focus(); #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 웹사이트 하이퍼링크 클릭시 처리하기 - webSiteHyperlink_Click(sender, e) /// <summary> /// 웹사이트 하이퍼링크 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void webSiteHyperlink_Click(object sender, RoutedEventArgs e) { Process.Start("http://www.charlespetzold.com"); } #endregion #region OK 버튼 클릭시 처리하기 - okButton_Click(sender, e) /// <summary> /// OK 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void okButton_Click(object sender, RoutedEventArgs e) { DialogResult = true; } #endregion } } |
▶ CommonDialog.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 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject { /// <summary> /// 공통 대화 상자 /// </summary> public abstract class CommonDialog : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Event ////////////////////////////////////////////////////////////////////////////////////////// Public #region 다음 찾기시 - FindNext /// <summary> /// 다음 찾기시 /// </summary> public event EventHandler FindNext; #endregion #region 대체시 - Replace /// <summary> /// 대체시 /// </summary> public event EventHandler Replace; #endregion #region 전체 대체시 - ReplaceAll /// <summary> /// 전체 대체시 /// </summary> public event EventHandler ReplaceAll; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Protected #region Field /// <summary> /// 대체 레이블 /// </summary> protected Label replaceLabel; /// <summary> /// 찾기 텍스트 박스 /// </summary> protected TextBox findTextBox; /// <summary> /// 대체 텍스트 박스 /// </summary> protected TextBox replaceTextBox; /// <summary> /// 대소문자 일치 체크 박스 /// </summary> protected CheckBox matchCaseCheckBox; /// <summary> /// 찾기 방향 그룹 박스 /// </summary> protected GroupBox findDirectionGroupBox; /// <summary> /// 아래 라디오 버튼 /// </summary> protected RadioButton downRadioButton; /// <summary> /// 위쪽 라디오 버튼 /// </summary> protected RadioButton upRadioButton; /// <summary> /// 찾기 버튼 /// </summary> protected Button findButton; /// <summary> /// 대체 버튼 /// </summary> protected Button replaceButton; /// <summary> /// 전체 대체 버튼 /// </summary> protected Button replaceAllButton; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 찾을 텍스트 - FindText /// <summary> /// 찾을 텍스트 /// </summary> public string FindText { set { this.findTextBox.Text = value; } get { return this.findTextBox.Text; } } #endregion #region 대체 텍스트 - ReplaceText /// <summary> /// 대체 텍스트 /// </summary> public string ReplaceText { set { this.replaceTextBox.Text = value; } get { return this.replaceTextBox.Text; } } #endregion #region 대소문자 일치 여부 - MatchCase /// <summary> /// 대소문자 일치 여부 /// </summary> public bool MatchCase { set { this.matchCaseCheckBox.IsChecked = value; } get { return (bool)this.matchCaseCheckBox.IsChecked; } } #endregion #region 찾기 방향 - FindDirection /// <summary> /// 찾기 방향 /// </summary> public FindDirection FindDirection { set { if(value == FindDirection.Down) { this.downRadioButton.IsChecked = true; } else { this.upRadioButton.IsChecked = true; } } get { return (bool)this.downRadioButton.IsChecked ? FindDirection.Down : FindDirection.Up; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 생성자 - CommonDialog(ownerWindow) /// <summary> /// 생성자 /// </summary> /// <param name="ownerWindow">소유자 윈도우</param> protected CommonDialog(Window ownerWindow) { ShowInTaskbar = false; WindowStyle = WindowStyle.ToolWindow; SizeToContent = SizeToContent.WidthAndHeight; WindowStartupLocation = WindowStartupLocation.CenterOwner; Owner = ownerWindow; FontFamily = new FontFamily("나눔고딕코딩"); FontSize = 16; Grid grid = new Grid(); Content = grid; for(int i = 0; i < 3; i++) { RowDefinition rowDefinition = new RowDefinition(); rowDefinition.Height = GridLength.Auto; grid.RowDefinitions.Add(rowDefinition); ColumnDefinition columnDefinition = new ColumnDefinition(); columnDefinition.Width = GridLength.Auto; grid.ColumnDefinitions.Add(columnDefinition); } #region 찾기 레이블 Label findLabel = new Label(); findLabel.Content = "Fi_nd what :"; findLabel.VerticalAlignment = VerticalAlignment.Center; findLabel.Margin = new Thickness(12); grid.Children.Add(findLabel); Grid.SetRow (findLabel, 0); Grid.SetColumn(findLabel, 0); #endregion #region 찾기 텍스트 박스 this.findTextBox = new TextBox(); this.findTextBox.Margin = new Thickness(12); this.findTextBox.TextChanged += findTextBox_TextChanged; grid.Children.Add(this.findTextBox); Grid.SetRow (this.findTextBox, 0); Grid.SetColumn(this.findTextBox, 1); #endregion #region 대체 레이블 this.replaceLabel = new Label(); this.replaceLabel.Content = "Re_place with :"; this.replaceLabel.VerticalAlignment = VerticalAlignment.Center; this.replaceLabel.Margin = new Thickness(12); grid.Children.Add(this.replaceLabel); Grid.SetRow (this.replaceLabel, 1); Grid.SetColumn(this.replaceLabel, 0); #endregion #region 대체 텍스트 박스 this.replaceTextBox = new TextBox(); this.replaceTextBox.Margin = new Thickness(12); grid.Children.Add(this.replaceTextBox); Grid.SetRow (this.replaceTextBox, 1); Grid.SetColumn(this.replaceTextBox, 1); #endregion #region 대소문자 일치 체크 박스 this.matchCaseCheckBox = new CheckBox(); this.matchCaseCheckBox.Content = "Match _case"; this.matchCaseCheckBox.VerticalAlignment = VerticalAlignment.Center; this.matchCaseCheckBox.Margin = new Thickness(12); grid.Children.Add(this.matchCaseCheckBox); Grid.SetRow (this.matchCaseCheckBox, 2); Grid.SetColumn(this.matchCaseCheckBox, 0); #endregion #region 찾기 방향 그룹 박스 this.findDirectionGroupBox = new GroupBox(); this.findDirectionGroupBox.Header = "Direction"; this.findDirectionGroupBox.Margin = new Thickness(12); this.findDirectionGroupBox.HorizontalAlignment = HorizontalAlignment.Left; grid.Children.Add(this.findDirectionGroupBox); Grid.SetRow (this.findDirectionGroupBox, 2); Grid.SetColumn(this.findDirectionGroupBox, 1); #endregion #region 찾기 방향 스택 패널 StackPanel findDirectionStackPanel = new StackPanel(); findDirectionStackPanel.Orientation = Orientation.Horizontal; this.findDirectionGroupBox.Content = findDirectionStackPanel; #endregion #region 위쪽 라디오 버튼 this.upRadioButton = new RadioButton(); this.upRadioButton.Content = "_Up"; this.upRadioButton.Margin = new Thickness(6); findDirectionStackPanel.Children.Add(this.upRadioButton); #endregion #region 아래쪽 라디오 버튼 this.downRadioButton = new RadioButton(); this.downRadioButton.Content = "_Down"; this.downRadioButton.Margin = new Thickness(6); findDirectionStackPanel.Children.Add(this.downRadioButton); #endregion #region 버튼 스택 패널 StackPanel buttonStackPanel = new StackPanel(); buttonStackPanel.Margin = new Thickness(6); grid.Children.Add(buttonStackPanel); Grid.SetRow (buttonStackPanel, 0); Grid.SetColumn (buttonStackPanel, 2); Grid.SetRowSpan(buttonStackPanel, 3); #endregion #region 찾기 버튼 this.findButton = new Button(); this.findButton.Content = "_Find Next"; this.findButton.Margin = new Thickness(6); this.findButton.IsDefault = true; this.findButton.Click += this.findButton_Click; buttonStackPanel.Children.Add(this.findButton); #endregion #region 대체 버튼 this.replaceButton = new Button(); this.replaceButton.Content = "_Replace"; this.replaceButton.Margin = new Thickness(6); this.replaceButton.Click += this.replaceButton_Click; buttonStackPanel.Children.Add(this.replaceButton); #endregion #region 전부 대체 버튼 this.replaceAllButton = new Button(); this.replaceAllButton.Content = "Replace _All"; this.replaceAllButton.Margin = new Thickness(6); this.replaceAllButton.Click += this.replaceAllButton_Click; buttonStackPanel.Children.Add(this.replaceAllButton); #endregion #region 취소 버튼 Button cancelButton = new Button(); cancelButton.Content = "Cancel"; cancelButton.Margin = new Thickness(6); cancelButton.IsCancel = true; cancelButton.Click += cancelButton_Click; buttonStackPanel.Children.Add(cancelButton); #endregion this.findTextBox.Focus(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 다음 찾기시 처리하기 - OnFindNext(e) /// <summary> /// 다음 찾기시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected virtual void OnFindNext(EventArgs e) { if(FindNext != null) { FindNext(this, e); } } #endregion #region 대체시 처리하기 - OnReplace(e) /// <summary> /// 대체시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected virtual void OnReplace(EventArgs e) { if(Replace != null) { Replace(this, e); } } #endregion #region 전부 대체시 처리하기 - OnReplaceAll(e) /// <summary> /// 전부 대체시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected virtual void OnReplaceAll(EventArgs e) { if(ReplaceAll != null) { ReplaceAll(this, e); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 찾기 텍스트 박스 텍스트 변경시 처리하기 - findTextBox_TextChanged(sender, e) /// <summary> /// 찾기 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void findTextBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox textBox = e.Source as TextBox; this.findButton.IsEnabled = this.replaceButton.IsEnabled = this.replaceAllButton.IsEnabled = (textBox.Text.Length > 0); } #endregion #region 찾기 버튼 클릭시 처리하기 - findButton_Click(sender, e) /// <summary> /// 찾기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void findButton_Click(object sender, RoutedEventArgs e) { OnFindNext(new EventArgs()); } #endregion #region 대체 버튼 클릭시 처리하기 - replaceButton_Click(sender, e) /// <summary> /// 대체 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void replaceButton_Click(object sender, RoutedEventArgs e) { OnReplace(new EventArgs()); } #endregion #region 전부 대체 버튼 클릭시 처리하기 - replaceAllButton_Click(sender, e) /// <summary> /// 전부 대체 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void replaceAllButton_Click(object sender, RoutedEventArgs e) { OnReplaceAll(new EventArgs()); } #endregion #region 취소 버튼 클릭시 처리하기 - cancelButton_Click(sender, e) /// <summary> /// 취소 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void cancelButton_Click(object sender, RoutedEventArgs e) { Close(); } #endregion } } |
▶ FindDialog.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 |
using System.Windows; namespace TestProject { /// <summary> /// 찾기 대화 상자 /// </summary> public class FindDialog : CommonDialog { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - FindDialog(ownerWindow) /// <summary> /// 생성자 /// </summary> /// <param name="ownerWindow">소유자 윈도우</param> public FindDialog(Window ownerWindow) : base(ownerWindow) { Title = "Find"; replaceLabel.Visibility = Visibility.Collapsed; replaceTextBox.Visibility = Visibility.Collapsed; replaceButton.Visibility = Visibility.Collapsed; replaceAllButton.Visibility = Visibility.Collapsed; } #endregion } } |
▶ FindDirection.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
namespace TestProject { /// <summary> /// 찾기 방향 /// </summary> public enum FindDirection { /// <summary> /// 아래 /// </summary> Down, /// <summary> /// 위 /// </summary> Up } } |
▶ FontDialog.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 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace TestProject { /// <summary> /// 폰트 대화 상자 /// </summary> public class FontDialog : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 패밀리 텍스트 리스터 /// </summary> private TextLister familyTextLister; /// <summary> /// 스타일 텍스트 리스터 /// </summary> private TextLister styleTextLister; /// <summary> /// 가중치 텍스트 리스터 /// </summary> private TextLister weightTextLister; /// <summary> /// 확장 텍스트 리스터 /// </summary> private TextLister stretchTextLister; /// <summary> /// 크기 텍스트 리스터 /// </summary> private TextLister sizeTextLister; /// <summary> /// 출력 레이블 /// </summary> private Label displayLabel; /// <summary> /// 샘플 텍스트 갱신 억제 여부 /// </summary> private bool isSampleTextUpdateSuppressed = true; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 타입 페이스 - Typeface /// <summary> /// 타입 페이스 /// </summary> public Typeface Typeface { set { if(this.familyTextLister.Contains(value.FontFamily)) { this.familyTextLister.SelectedItem = value.FontFamily; } else { this.familyTextLister.SelectedIndex = 0; } if(this.styleTextLister.Contains(value.Style)) { this.styleTextLister.SelectedItem = value.Style; } else { this.styleTextLister.SelectedIndex = 0; } if(this.weightTextLister.Contains(value.Weight)) { this.weightTextLister.SelectedItem = value.Weight; } else { this.weightTextLister.SelectedIndex = 0; } if(this.stretchTextLister.Contains(value.Stretch)) { this.stretchTextLister.SelectedItem = value.Stretch; } else { this.stretchTextLister.SelectedIndex = 0; } } get { return new Typeface ( (FontFamily)this.familyTextLister.SelectedItem, (FontStyle)this.styleTextLister.SelectedItem, (FontWeight)this.weightTextLister.SelectedItem, (FontStretch)this.stretchTextLister.SelectedItem ); } } #endregion #region 페이스 크기 - FaceSize /// <summary> /// 페이스 크기 /// </summary> public double FaceSize { set { double size = 0.75d * value; this.sizeTextLister.Text = size.ToString(); if(!this.sizeTextLister.Contains(size)) { this.sizeTextLister.Insert(0, size); } this.sizeTextLister.SelectedItem = size; } get { double size; if(!Double.TryParse(this.sizeTextLister.Text, out size)) { size = 8.25d; } return size / 0.75d; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - FontDialog() /// <summary> /// 생성자 /// </summary> public FontDialog() { Title = "폰트"; ShowInTaskbar = false; WindowStyle = WindowStyle.ToolWindow; WindowStartupLocation = WindowStartupLocation.CenterOwner; SizeToContent = SizeToContent.WidthAndHeight; ResizeMode = ResizeMode.NoResize; FontFamily = new FontFamily("나눔고딕코딩"); FontSize = 16; Grid mainGrid = new Grid(); Content = mainGrid; #region 메인 컨트롤 행 정의 RowDefinition mainControlRowDefinition = new RowDefinition(); mainControlRowDefinition.Height = new GridLength(200, GridUnitType.Pixel); mainGrid.RowDefinitions.Add(mainControlRowDefinition); #endregion #region 메인 샘플 텍스트 행 정의 RowDefinition mainSampleTextRowDefinition = new RowDefinition(); mainSampleTextRowDefinition.Height = new GridLength(150, GridUnitType.Pixel); mainGrid.RowDefinitions.Add(mainSampleTextRowDefinition); #endregion #region 메인 버튼 행 정의 RowDefinition mainButtonRowDefinition = new RowDefinition(); mainButtonRowDefinition.Height = GridLength.Auto; mainGrid.RowDefinitions.Add(mainButtonRowDefinition); #endregion #region 메인 컬럼 정의 ColumnDefinition mainColumnDefinition = new ColumnDefinition(); mainColumnDefinition.Width = new GridLength(650, GridUnitType.Pixel); mainGrid.ColumnDefinitions.Add(mainColumnDefinition); #endregion Grid controlGrid = new Grid(); mainGrid.Children.Add(controlGrid); #region 컨트롤 레이블 행 정의 RowDefinition controlLabelRowDefinition = new RowDefinition(); controlLabelRowDefinition.Height = GridLength.Auto; controlGrid.RowDefinitions.Add(controlLabelRowDefinition); #endregion #region 컨트롤 컨트롤 행 정의 RowDefinition controlControlRowDefinition = new RowDefinition(); controlControlRowDefinition.Height = new GridLength(100, GridUnitType.Star); controlGrid.RowDefinitions.Add(controlControlRowDefinition); #endregion #region 컨트롤 패밀리 컬럼 정의 ColumnDefinition controlFamilyColumnDefinition = new ColumnDefinition(); controlFamilyColumnDefinition.Width = new GridLength(175, GridUnitType.Star); controlGrid.ColumnDefinitions.Add(controlFamilyColumnDefinition); #endregion #region 컨트롤 스타일 컬럼 정의 ColumnDefinition controlStyleColumnDefinition = new ColumnDefinition(); controlStyleColumnDefinition.Width = new GridLength(100, GridUnitType.Star); controlGrid.ColumnDefinitions.Add(controlStyleColumnDefinition); #endregion #region 컨트롤 가중치 컬럼 정의 ColumnDefinition controlWeightColumnDefinition = new ColumnDefinition(); controlWeightColumnDefinition.Width = new GridLength(100, GridUnitType.Star); controlGrid.ColumnDefinitions.Add(controlWeightColumnDefinition); #endregion #region 컨트롤 확장 컬럼 정의 ColumnDefinition controlStretchColumnDefinition = new ColumnDefinition(); controlStretchColumnDefinition.Width = new GridLength(100, GridUnitType.Star); controlGrid.ColumnDefinitions.Add(controlStretchColumnDefinition); #endregion #region 컨트롤 크기 컬럼 정의 ColumnDefinition controlSizeColumnDefinition = new ColumnDefinition(); controlSizeColumnDefinition.Width = new GridLength(75, GridUnitType.Star); controlGrid.ColumnDefinitions.Add(controlSizeColumnDefinition); #endregion #region 패밀리 레이블 Label familyLabel = new Label(); familyLabel.Content = "Font Family"; familyLabel.Margin = new Thickness(12, 12, 12, 0); controlGrid.Children.Add(familyLabel); Grid.SetRow (familyLabel, 0); Grid.SetColumn(familyLabel, 0); #endregion #region 패밀리 텍스트 리스터 this.familyTextLister = new TextLister(); this.familyTextLister.IsReadOnly = true; this.familyTextLister.Margin = new Thickness(12, 0, 12, 12); controlGrid.Children.Add(this.familyTextLister); Grid.SetRow (this.familyTextLister, 1); Grid.SetColumn(this.familyTextLister, 0); #endregion #region 스타일 레이블 Label styleLabel = new Label(); styleLabel.Content = "Style"; styleLabel.Margin = new Thickness(12, 12, 12, 0); controlGrid.Children.Add(styleLabel); Grid.SetRow (styleLabel, 0); Grid.SetColumn(styleLabel, 1); #endregion #region 스타일 텍스트 리스터 this.styleTextLister = new TextLister(); this.styleTextLister.IsReadOnly = true; this.styleTextLister.Margin = new Thickness(12, 0, 12, 12); controlGrid.Children.Add(this.styleTextLister); Grid.SetRow (this.styleTextLister, 1); Grid.SetColumn(this.styleTextLister, 1); #endregion #region 가중치 레이블 Label weightLabel = new Label(); weightLabel.Content = "Weight"; weightLabel.Margin = new Thickness(12, 12, 12, 0); controlGrid.Children.Add(weightLabel); Grid.SetRow (weightLabel, 0); Grid.SetColumn(weightLabel, 2); #endregion #region 가중치 텍스트 리스터 this.weightTextLister = new TextLister(); this.weightTextLister.IsReadOnly = true; this.weightTextLister.Margin = new Thickness(12, 0, 12, 12); controlGrid.Children.Add(this.weightTextLister); Grid.SetRow (this.weightTextLister, 1); Grid.SetColumn(this.weightTextLister, 2); #endregion #region 확장 레이블 Label stretchLabel = new Label(); stretchLabel.Content = "Stretch"; stretchLabel.Margin = new Thickness(12, 12, 12, 0); controlGrid.Children.Add(stretchLabel); Grid.SetRow (stretchLabel, 0); Grid.SetColumn(stretchLabel, 3); #endregion #region 확장 텍스트 리스터 this.stretchTextLister = new TextLister(); this.stretchTextLister.IsReadOnly = true; this.stretchTextLister.Margin = new Thickness(12, 0, 12, 12); controlGrid.Children.Add(this.stretchTextLister); Grid.SetRow (this.stretchTextLister, 1); Grid.SetColumn(this.stretchTextLister, 3); #endregion #region 크기 레이블 Label sizeLabel = new Label(); sizeLabel.Content = "Size"; sizeLabel.Margin = new Thickness(12, 12, 12, 0); controlGrid.Children.Add(sizeLabel); Grid.SetRow (sizeLabel, 0); Grid.SetColumn(sizeLabel, 4); #endregion #region 크기 텍스트 리스터 this.sizeTextLister = new TextLister(); this.sizeTextLister.Margin = new Thickness(12, 0, 12, 12); controlGrid.Children.Add(this.sizeTextLister); Grid.SetRow (this.sizeTextLister, 1); Grid.SetColumn(this.sizeTextLister, 4); #endregion #region 출력 레이블 this.displayLabel = new Label(); this.displayLabel.Content = "AaBbCc XxYzZz 012345"; this.displayLabel.HorizontalContentAlignment = HorizontalAlignment.Center; this.displayLabel.VerticalContentAlignment = VerticalAlignment.Center; mainGrid.Children.Add(this.displayLabel); Grid.SetRow(this.displayLabel, 1); #endregion Grid buttonGrid = new Grid(); mainGrid.Children.Add(buttonGrid); Grid.SetRow(buttonGrid, 2); for(int i = 0; i < 5; i++) { buttonGrid.ColumnDefinitions.Add(new ColumnDefinition()); } #region OK 버튼 Button okButton = new Button(); okButton.Content = "OK"; okButton.IsDefault = true; okButton.HorizontalAlignment = HorizontalAlignment.Center; okButton.MinWidth = 60; okButton.Margin = new Thickness(12); okButton.Click += okButton_Click; buttonGrid.Children.Add(okButton); Grid.SetColumn(okButton, 1); #endregion #region Cancel 버튼 Button cancelButton = new Button(); cancelButton.Content = "Cancel"; cancelButton.IsCancel = true; cancelButton.HorizontalAlignment = HorizontalAlignment.Center; cancelButton.MinWidth = 60; cancelButton.Margin = new Thickness(12); buttonGrid.Children.Add(cancelButton); Grid.SetColumn(cancelButton, 3); #endregion #region 패밀리 텍스트 리스터를 설정한다. foreach(FontFamily fontFamily in Fonts.SystemFontFamilies) { this.familyTextLister.Add(fontFamily); } #endregion #region 크기 텍스트 리스터를 설정한다. double[] sizeArray = new double[] { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72 }; foreach(double size in sizeArray) { this.sizeTextLister.Add(size); } #endregion this.familyTextLister.SelectionChanged += familyTextLister_SelectionChanged; this.styleTextLister.SelectionChanged += textLister_SelectionChanged; this.weightTextLister.SelectionChanged += textLister_SelectionChanged; this.stretchTextLister.SelectionChanged += textLister_SelectionChanged; this.sizeTextLister.TextChanged += sizeTextLister_TextChanged; Typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch); FaceSize = FontSize; this.familyTextLister.Focus(); this.isSampleTextUpdateSuppressed = false; UpdateSample(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 패밀리 텍스트 리스터 선택 변경시 처리하기 - familyTextLister_SelectionChanged(sender, e) /// <summary> /// 패밀리 텍스트 리스터 선택 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void familyTextLister_SelectionChanged(object sender, EventArgs e) { FontFamily fontFamily = (FontFamily)this.familyTextLister.SelectedItem; FontStyle? previousFontStyle = (FontStyle?)this.styleTextLister.SelectedItem; FontWeight? previousFontWeight = (FontWeight?)this.weightTextLister.SelectedItem; FontStretch? previousFontStretch = (FontStretch?)this.stretchTextLister.SelectedItem; this.isSampleTextUpdateSuppressed = true; this.styleTextLister.Clear(); this.weightTextLister.Clear(); this.stretchTextLister.Clear(); foreach(FamilyTypeface familyTypeface in fontFamily.FamilyTypefaces) { if(!this.styleTextLister.Contains(familyTypeface.Style)) { if(familyTypeface.Style == FontStyles.Normal) { this.styleTextLister.Insert(0, familyTypeface.Style); } else { this.styleTextLister.Add(familyTypeface.Style); } } if(!this.weightTextLister.Contains(familyTypeface.Weight)) { if(familyTypeface.Weight == FontWeights.Normal) { this.weightTextLister.Insert(0, familyTypeface.Weight); } else { this.weightTextLister.Add(familyTypeface.Weight); } } if(!this.stretchTextLister.Contains(familyTypeface.Stretch)) { if(familyTypeface.Stretch == FontStretches.Normal) { this.stretchTextLister.Insert(0, familyTypeface.Stretch); } else { this.stretchTextLister.Add(familyTypeface.Stretch); } } } if(this.styleTextLister.Contains(previousFontStyle)) { this.styleTextLister.SelectedItem = previousFontStyle; } else { this.styleTextLister.SelectedIndex = 0; } if(this.weightTextLister.Contains(previousFontWeight)) { this.weightTextLister.SelectedItem = previousFontWeight; } else { this.weightTextLister.SelectedIndex = 0; } if(this.stretchTextLister.Contains(previousFontStretch)) { this.stretchTextLister.SelectedItem = previousFontStretch; } else { this.stretchTextLister.SelectedIndex = 0; } this.isSampleTextUpdateSuppressed = false; UpdateSample(); } #endregion #region 텍스트 리스터 선택 변경시 처리하기 - textLister_SelectionChanged(sender, e) /// <summary> /// 텍스트 리스터 선택 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void textLister_SelectionChanged(object sender, EventArgs e) { UpdateSample(); } #endregion #region 크기 텍스트 리스터 텍스트 변경시 처리하기 - sizeTextLister_TextChanged(sender, e) /// <summary> /// 크기 텍스트 리스터 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void sizeTextLister_TextChanged(object sender, TextChangedEventArgs e) { UpdateSample(); } #endregion #region OK 버튼 클릭시 처리하기 - okButton_Click(sender, e) /// <summary> /// OK 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void okButton_Click(object sender, RoutedEventArgs e) { DialogResult = true; } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 샘플 갱신하기 - UpdateSample() /// <summary> /// 샘플 갱신하기 /// </summary> private void UpdateSample() { if(this.isSampleTextUpdateSuppressed) { return; } this.displayLabel.FontFamily = (FontFamily)this.familyTextLister.SelectedItem; this.displayLabel.FontStyle = (FontStyle)this.styleTextLister.SelectedItem; this.displayLabel.FontWeight = (FontWeight)this.weightTextLister.SelectedItem; this.displayLabel.FontStretch = (FontStretch)this.stretchTextLister.SelectedItem; double size; if(!Double.TryParse(this.sizeTextLister.Text, out size)) { size = 8.25d; } this.displayLabel.FontSize = size / 0.75d; } #endregion } } |
▶ Lister.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 |
using System; using System.Collections; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace TestProject { /// <summary> /// 리스터 /// </summary> public class Lister : ContentControl { //////////////////////////////////////////////////////////////////////////////////////////////////// Event ////////////////////////////////////////////////////////////////////////////////////////// Public #region 선택 변경시 - SelectionChanged /// <summary> /// 선택 변경시 /// </summary> public event EventHandler SelectionChanged; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 스크롤 뷰어 /// </summary> private ScrollViewer scrollViewer; /// <summary> /// 스택 패널 /// </summary> private StackPanel stackPanel; /// <summary> /// 배열 리스트 /// </summary> private ArrayList arrayList = new ArrayList(); /// <summary> /// 선택 인덱스 /// </summary> private int selectedIndex = -1; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 수 - Count /// <summary> /// 수 /// </summary> public int Count { get { return this.arrayList.Count; } } #endregion #region 선택 인덱스 - SelectedIndex /// <summary> /// 선택 인덱스 /// </summary> public int SelectedIndex { set { if(value < -1 || value >= Count) { throw new ArgumentOutOfRangeException("SelectedIndex"); } if(value == this.selectedIndex) { return; } if(this.selectedIndex != -1) { TextBlock textBlock = this.stackPanel.Children[this.selectedIndex] as TextBlock; textBlock.Background = SystemColors.WindowBrush; textBlock.Foreground = SystemColors.WindowTextBrush; } this.selectedIndex = value; if(this.selectedIndex > -1) { TextBlock textBlock = this.stackPanel.Children[this.selectedIndex] as TextBlock; textBlock.Background = SystemColors.HighlightBrush; textBlock.Foreground = SystemColors.HighlightTextBrush; } ScrollIntoView(); OnSelectionChanged(EventArgs.Empty); } get { return this.selectedIndex; } } #endregion #region 선택 항목 - SelectedItem /// <summary> /// 선택 항목 /// </summary> public object SelectedItem { set { SelectedIndex = this.arrayList.IndexOf(value); } get { if(SelectedIndex > -1) { return this.arrayList[SelectedIndex]; } return null; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Lister() /// <summary> /// 생성자 /// </summary> public Lister() { Focusable = false; Border border = new Border(); border.BorderThickness = new Thickness(1d); border.BorderBrush = SystemColors.ActiveBorderBrush; border.Background = SystemColors.WindowBrush; Content = border; this.scrollViewer = new ScrollViewer(); this.scrollViewer.Focusable = false; this.scrollViewer.Padding = new Thickness(2, 0, 0, 0); border.Child = this.scrollViewer; this.stackPanel = new StackPanel(); this.scrollViewer.Content = this.stackPanel; AddHandler ( TextBlock.MouseLeftButtonDownEvent, new MouseButtonEventHandler(textBlock_MouseLeftButtonDown) ); Loaded += ContentControl_Loaded; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 지우기 - Clear() /// <summary> /// 지우기 /// </summary> public void Clear() { SelectedIndex = -1; this.stackPanel.Children.Clear(); this.arrayList.Clear(); } #endregion #region 추가하기 - Add(item) /// <summary> /// 추가하기 /// </summary> /// <param name="item">항목</param> public void Add(object item) { this.arrayList.Add(item); TextBlock textBlock = new TextBlock(); textBlock.Text = item.ToString(); this.stackPanel.Children.Add(textBlock); } #endregion #region 삽입하기 - Insert(index, item) /// <summary> /// 삽입하기 /// </summary> /// <param name="index">인덱스</param> /// <param name="item">항목</param> public void Insert(int index, object item) { this.arrayList.Insert(index, item); TextBlock textBlock = new TextBlock(); textBlock.Text = item.ToString(); this.stackPanel.Children.Insert(index, textBlock); } #endregion #region 포함 여부 구하기 - Contains(item) /// <summary> /// 포함 여부 구하기 /// </summary> /// <param name="item">항목</param> /// <returns>포함 여부</returns> public bool Contains(object item) { return this.arrayList.Contains(item); } #endregion #region 문자로 이동하기 - GoToLetter(character) /// <summary> /// 문자로 이동하기 /// </summary> /// <param name="character">문자</param> public void GoToLetter(char character) { int offset = SelectedIndex + 1; for(int i = 0; i < Count; i++) { int index = (i + offset) % Count; if(Char.ToUpper(character) == Char.ToUpper(this.arrayList[index].ToString()[0])) { SelectedIndex = index; break; } } } #endregion #region 페이지 UP 처리하기 - PageUp() /// <summary> /// 페이지 UP 처리하기 /// </summary> public void PageUp() { if(SelectedIndex == -1 || Count == 0) { return; } int index = SelectedIndex - (int)(Count * this.scrollViewer.ViewportHeight / this.scrollViewer.ExtentHeight); if(index < 0) { index = 0; } SelectedIndex = index; } #endregion #region 페이지 DOWN 처리하기 - PageDown() /// <summary> /// 페이지 DOWN 처리하기 /// </summary> public void PageDown() { if(SelectedIndex == -1 || Count == 0) { return; } int index = SelectedIndex + (int)(Count * this.scrollViewer.ViewportHeight / this.scrollViewer.ExtentHeight); if(index > Count - 1) { index = Count - 1; } SelectedIndex = index; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 선택 변경시 처리하기 - OnSelectionChanged(e) /// <summary> /// 선택 변경시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected virtual void OnSelectionChanged(EventArgs e) { if(SelectionChanged != null) { SelectionChanged(this, e); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 컨텐트 컨트롤 로드시 처리하기 - ContentControl_Loaded(sender, e) /// <summary> /// 컨텐트 컨트롤 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void ContentControl_Loaded(object sender, RoutedEventArgs e) { ScrollIntoView(); } #endregion #region 텍스트 블럭 마우스 왼쪽 버튼 다운시 처리하기 - textBlock_MouseLeftButtonDown(sender, e) /// <summary> /// 텍스트 블럭 마우스 왼쪽 버튼 다운시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void textBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if(e.Source is TextBlock) { SelectedIndex = this.stackPanel.Children.IndexOf(e.Source as TextBlock); } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 항목이 보이게 스크롤 하기 - ScrollIntoView() /// <summary> /// 항목이 보이게 스크롤 하기 /// </summary> private void ScrollIntoView() { if(Count == 0 || SelectedIndex == -1 || this.scrollViewer.ViewportHeight > this.scrollViewer.ExtentHeight) { return; } double itemHeight = this.scrollViewer.ExtentHeight / Count; double itemTopOffset = SelectedIndex * itemHeight; double itemBottomOffset = (SelectedIndex + 1) * itemHeight; if(itemTopOffset < this.scrollViewer.VerticalOffset) { this.scrollViewer.ScrollToVerticalOffset(itemTopOffset); } else if(itemBottomOffset > this.scrollViewer.VerticalOffset + this.scrollViewer.ViewportHeight) { this.scrollViewer.ScrollToVerticalOffset(itemBottomOffset - this.scrollViewer.ViewportHeight); } } #endregion } } |
▶ MainWindow.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 |
using System; using System.ComponentModel; using System.IO; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Media; namespace TestProject { /// <summary> /// 메인 윈도우 /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Protected #region Field /// <summary> /// 애플리케이션 제목 /// </summary> protected string applicationTitle; /// <summary> /// 설정 파일 경로 /// </summary> protected string settingFilePath; /// <summary> /// 노트패드 클론 설정 /// </summary> protected NotepadCloneSetting notepadCloneSetting; /// <summary> /// 파일 수정 여부 /// </summary> protected bool isFileDirty = false; /// <summary> /// 메뉴 /// </summary> protected Menu menu; /// <summary> /// 텍스트 박스 /// </summary> protected TextBox textBox; /// <summary> /// 상태 바 /// </summary> protected StatusBar statusBar; #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 파일 경로 /// </summary> private string filePath; /// <summary> /// 상태 바 항목 /// </summary> private StatusBarItem statusBarItem; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainWindow() /// <summary> /// 생성자 /// </summary> public MainWindow() { Width = 800; Height = 600; FontFamily = new FontFamily("나눔고딕코딩"); FontSize = 16; Assembly assembly = Assembly.GetExecutingAssembly(); #region 애플리케이션 제목 AssemblyTitleAttribute assemblyTitleAttribute = (AssemblyTitleAttribute)assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false)[0]; this.applicationTitle = assemblyTitleAttribute.Title; #endregion AssemblyProductAttribute assemblyProductAttribute = (AssemblyProductAttribute)assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0]; this.settingFilePath = Path.Combine ( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TEMP\\" + assemblyProductAttribute.Product + "\\" + assemblyProductAttribute.Product + ".Settings.xml" ); DockPanel dockPanel = new DockPanel(); Content = dockPanel; this.menu = new Menu(); this.menu.FontFamily = FontFamily; this.menu.FontSize = FontSize; dockPanel.Children.Add(this.menu); DockPanel.SetDock(this.menu, Dock.Top); this.statusBar = new StatusBar(); this.statusBar.FontFamily = FontFamily; this.statusBar.FontSize = FontSize; dockPanel.Children.Add(this.statusBar); DockPanel.SetDock(this.statusBar, Dock.Bottom); this.statusBarItem = new StatusBarItem(); this.statusBarItem.HorizontalAlignment = HorizontalAlignment.Right; this.statusBar.Items.Add(this.statusBarItem); this.textBox = new TextBox(); this.textBox.AcceptsReturn = true; this.textBox.AcceptsTab = true; this.textBox.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; this.textBox.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto; this.textBox.TextChanged += textBox_TextChanged; this.textBox.SelectionChanged += textBox_SelectionChanged; dockPanel.Children.Add(this.textBox); AddFileMenu(this.menu); AddEditMenu(this.menu); AddFormatMenu(this.menu); AddViewMenu(this.menu); AddHelpMenu(this.menu); this.notepadCloneSetting = (NotepadCloneSetting)LoadSetting(); WindowState = this.notepadCloneSetting.WindowState; if(this.notepadCloneSetting.RestoreBounds != Rect.Empty) { Left = this.notepadCloneSetting.RestoreBounds.Left; Top = this.notepadCloneSetting.RestoreBounds.Top; Width = this.notepadCloneSetting.RestoreBounds.Width; Height = this.notepadCloneSetting.RestoreBounds.Height; } this.textBox.TextWrapping = this.notepadCloneSetting.TextWrapping; this.textBox.FontFamily = new FontFamily(this.notepadCloneSetting.FontFamily); this.textBox.FontStyle = (FontStyle)(new FontStyleConverter().ConvertFromString(this.notepadCloneSetting.FontStyle)); this.textBox.FontWeight = (FontWeight)(new FontWeightConverter().ConvertFromString(this.notepadCloneSetting.FontWeight)); this.textBox.FontStretch = (FontStretch)(new FontStretchConverter().ConvertFromString(this.notepadCloneSetting.FontStretch)); this.textBox.FontSize = this.notepadCloneSetting.FontSize; Loaded += Window_Loaded; this.textBox.Focus(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> [STAThread] public static void Main() { Application application = new Application(); application.ShutdownMode = ShutdownMode.OnMainWindowClose; application.Run(new MainWindow()); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Instance //////////////////////////////////////////////////////////////////////////////// Protected #region 닫을 경우 처리하기 - OnClosing(e) /// <summary> /// 닫을 경우 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); e.Cancel = !CheckToTrash(); this.notepadCloneSetting.RestoreBounds = RestoreBounds; } #endregion #region 닫는 경우 처리하기 - OnClosed(e) /// <summary> /// 닫는 경우 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnClosed(EventArgs e) { base.OnClosed(e); this.notepadCloneSetting.WindowState = WindowState; this.notepadCloneSetting.TextWrapping = this.textBox.TextWrapping; this.notepadCloneSetting.FontFamily = this.textBox.FontFamily.ToString(); this.notepadCloneSetting.FontStyle = new FontStyleConverter().ConvertToString(this.textBox.FontStyle); this.notepadCloneSetting.FontWeight = new FontWeightConverter().ConvertToString(this.textBox.FontWeight); this.notepadCloneSetting.FontStretch = new FontStretchConverter().ConvertToString(this.textBox.FontStretch); this.notepadCloneSetting.FontSize = this.textBox.FontSize; SaveSetting(); } #endregion #region 설정 로드하기 - LoadSetting() /// <summary> /// 설정 로드하기 /// </summary> /// <returns>NotepadCloneSetting 객체</returns> protected virtual object LoadSetting() { return NotepadCloneSetting.Load(typeof(NotepadCloneSetting), this.settingFilePath); } #endregion #region 설정 저장하기 - SaveSetting() /// <summary> /// 설정 저장하기 /// </summary> protected virtual void SaveSetting() { this.notepadCloneSetting.Save(this.settingFilePath); } #endregion #region 제목 갱신하기 - UpdateTitle() /// <summary> /// 제목 갱신하기 /// </summary> protected void UpdateTitle() { if(this.filePath == null) { Title = "Untitled - " + this.applicationTitle; } else { Title = Path.GetFileName(this.filePath) + " - " + this.applicationTitle; } } #endregion //////////////////////////////////////////////////////////////////////////////// Private ////////////////////////////////////////////////////////////////////// Event #region 윈도우 로드시 처리하기 - Window_Loaded(sender, e) /// <summary> /// 윈도우 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Window_Loaded(object sender, RoutedEventArgs e) { ApplicationCommands.New.Execute(null, this); string[] argumentArray = Environment.GetCommandLineArgs(); if(argumentArray.Length > 1) { if(File.Exists(argumentArray[1])) { LoadFile(argumentArray[1]); } else { MessageBoxResult messageBoxResult = MessageBox.Show ( "Cannot find the " + Path.GetFileName(argumentArray[1]) + " file.\r\n\r\n" + "Do you want to create a new file?", this.applicationTitle, MessageBoxButton.YesNoCancel, MessageBoxImage.Question ); if(messageBoxResult == MessageBoxResult.Cancel) { Close(); } else if(messageBoxResult == MessageBoxResult.Yes) { try { File.Create(this.filePath = argumentArray[1]).Close(); } catch(Exception exception) { MessageBox.Show ( "Error on File Creation: " + exception.Message, this.applicationTitle, MessageBoxButton.OK, MessageBoxImage.Asterisk ); return; } UpdateTitle(); } } } } #endregion #region 텍스트 박스 텍스트 변경시 처리하기 - textBox_TextChanged(sender, e) /// <summary> /// 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void textBox_TextChanged(object sender, RoutedEventArgs e) { this.isFileDirty = true; } #endregion #region 텍스트 박스 선택 변경시 처리하기 - textBox_SelectionChanged(sender, e) /// <summary> /// 텍스트 박스 선택 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void textBox_SelectionChanged(object sender, RoutedEventArgs e) { int selectionStart = this.textBox.SelectionStart; int row = this.textBox.GetLineIndexFromCharacterIndex(selectionStart); if(row == -1) { this.statusBarItem.Content = string.Empty; return; } int column = selectionStart - this.textBox.GetCharacterIndexFromLineIndex(row); string location = string.Format("Line {0} Col {1}", row + 1, column + 1); if(this.textBox.SelectionLength > 0) { selectionStart += this.textBox.SelectionLength; row = this.textBox.GetLineIndexFromCharacterIndex(selectionStart); column = selectionStart - this.textBox.GetCharacterIndexFromLineIndex(row); location += string.Format(" - Line {0} Col {1}", row + 1, column + 1); } this.statusBarItem.Content = location; } #endregion } } |
▶ MainWindow.Edit.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 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace TestProject { /// <summary> /// 메인 윈도우 (Edit) /// </summary> public partial class MainWindow { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region Undo 실행시 처리하기 - Undo_Executed(sender, e) /// <summary> /// Undo 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Undo_Executed(object sender, ExecutedRoutedEventArgs e) { this.textBox.Undo(); } #endregion #region Undo 실행 가능 여부 조사하기 - UndoCanExecute(sender, e) /// <summary> /// Undo 실행 가능 여부 조사하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void UndoCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = this.textBox.CanUndo; } #endregion #region Redo 실행시 처리하기 - Redo_Executed(sender, e) /// <summary> /// Redo 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Redo_Executed(object sender, ExecutedRoutedEventArgs e) { this.textBox.Redo(); } #endregion #region Redo 실행 가능 여부 조사하기 - RedoCanExecute(sender, e) /// <summary> /// Redo 실행 가능 여부 조사하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void RedoCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = this.textBox.CanRedo; } #endregion #region Cut 실행시 처리하기 - Cut_Executed(sender, e) /// <summary> /// Cut 실행시 처리하기 /// </summary> /// <param name="sender"></param> /// <param name="e">이벤트 인자</param> private void Cut_Executed(object sender, ExecutedRoutedEventArgs e) { this.textBox.Cut(); } #endregion #region Cut 실행 가능 여부 조사하기 - CutCanExecute(sender, e) /// <summary> /// Cut 실행 가능 여부 조사하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void CutCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = this.textBox.SelectedText.Length > 0; } #endregion #region Copy 실행시 처리하기 - Copy_Executed(sender, e) /// <summary> /// Copy 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Copy_Executed(object sender, ExecutedRoutedEventArgs e) { this.textBox.Copy(); } #endregion #region Delete 실행시 처리하기 - Delete_Executed(sender, e) /// <summary> /// Delete 실행시 처리하기 /// </summary> /// <param name="sender"></param> /// <param name="e">이벤트 인자</param> private void Delete_Executed(object sender, ExecutedRoutedEventArgs e) { this.textBox.SelectedText = string.Empty; } #endregion #region Paste 실행시 처리하기 - Paste_Executed(sender, e) /// <summary> /// Paste 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Paste_Executed(object sender, ExecutedRoutedEventArgs e) { this.textBox.Paste(); } #endregion #region Paste 실행 가능 여부 조사하기 - PasteCanExecute(sender, e) /// <summary> /// Paste 실행 가능 여부 조사하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void PasteCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = Clipboard.ContainsText(); } #endregion #region Select All 실행시 처리하기 - SelectAll_Executed(sender, e) /// <summary> /// Select All 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void SelectAll_Executed(object sender, ExecutedRoutedEventArgs e) { this.textBox.SelectAll(); } #endregion #region Time/Date 실행시 처리하기 - TimeDate_Executed(sender, e) /// <summary> /// Time/Date 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void TimeDate_Executed(object sender, ExecutedRoutedEventArgs e) { this.textBox.SelectedText = DateTime.Now.ToString(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region Edit 메뉴 추가하기 - AddEditMenu(menu) /// <summary> /// Edit 메뉴 추가하기 /// </summary> /// <param name="menu">Menu 객체</param> private void AddEditMenu(Menu menu) { #region Edit 메뉴 항목 MenuItem editMenuItem = new MenuItem(); editMenuItem.Header = "_Edit"; menu.Items.Add(editMenuItem); #endregion #region Undo 메뉴 항목 MenuItem undoMenuItem = new MenuItem(); undoMenuItem.Header = "_Undo"; undoMenuItem.Command = ApplicationCommands.Undo; editMenuItem.Items.Add(undoMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo, Undo_Executed, UndoCanExecute)); #endregion #region Redo 메뉴 항목 MenuItem redoMenuItem = new MenuItem(); redoMenuItem.Header = "_Redo"; redoMenuItem.Command = ApplicationCommands.Redo; editMenuItem.Items.Add(redoMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.Redo, Redo_Executed, RedoCanExecute)); #endregion editMenuItem.Items.Add(new Separator()); #region Cut 메뉴 항목 MenuItem cutMenuItem = new MenuItem(); cutMenuItem.Header = "Cu_t"; cutMenuItem.Command = ApplicationCommands.Cut; editMenuItem.Items.Add(cutMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.Cut, Cut_Executed, CutCanExecute)); #endregion #region Copy 메뉴 항목 MenuItem copyMenuItem = new MenuItem(); copyMenuItem.Header = "_Copy"; copyMenuItem.Command = ApplicationCommands.Copy; editMenuItem.Items.Add(copyMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, Copy_Executed, CutCanExecute)); #endregion #region Paste 메뉴 항목 MenuItem pasteMenuItem = new MenuItem(); pasteMenuItem.Header = "_Paste"; pasteMenuItem.Command = ApplicationCommands.Paste; editMenuItem.Items.Add(pasteMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste, Paste_Executed, PasteCanExecute)); #endregion #region Delete 메뉴 항목 MenuItem deleteMenuItem = new MenuItem(); deleteMenuItem.Header = "De_lete"; deleteMenuItem.Command = ApplicationCommands.Delete; editMenuItem.Items.Add(deleteMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.Delete, Delete_Executed, CutCanExecute)); #endregion editMenuItem.Items.Add(new Separator()); AddFindMenuItems(editMenuItem); editMenuItem.Items.Add(new Separator()); #region Select All 메뉴 항목 MenuItem selectAllMenuItem = new MenuItem(); selectAllMenuItem.Header = "Select _All"; selectAllMenuItem.Command = ApplicationCommands.SelectAll; editMenuItem.Items.Add(selectAllMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.SelectAll, SelectAll_Executed)); #endregion #region Time/Date 메뉴 항목 InputGestureCollection inputGestureCollection = new InputGestureCollection(); inputGestureCollection.Add(new KeyGesture(Key.F5)); RoutedUICommand timeDateRoutedUICommand = new RoutedUICommand("Time/_Date", "TimeDate", GetType(), inputGestureCollection); MenuItem timeDateMenuItem = new MenuItem(); timeDateMenuItem.Command = timeDateRoutedUICommand; editMenuItem.Items.Add(timeDateMenuItem); CommandBindings.Add(new CommandBinding(timeDateRoutedUICommand, TimeDate_Executed)); #endregion } #endregion } } |
▶ MainWindow.File.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 |
using Microsoft.Win32; using System; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace TestProject { /// <summary> /// 메인 윈도우 (File) /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Protected #region Field /// <summary> /// 필터 /// </summary> protected string filter = "Text Documents(*.txt)|*.txt|All Files(*.*)|*.*"; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region New 실행시 처리하기 - New_Executed(sender, e) /// <summary> /// New 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected virtual void New_Executed(object sender, ExecutedRoutedEventArgs e) { if(!CheckToTrash()) { return; } this.textBox.Text = string.Empty; filePath = null; isFileDirty = false; UpdateTitle(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region Open 실행시 처리하기 - Open_Executed(sender, e) /// <summary> /// Open 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Open_Executed(object sender, ExecutedRoutedEventArgs e) { if(!CheckToTrash()) { return; } OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = this.filter; if((bool)openFileDialog.ShowDialog(this)) { LoadFile(openFileDialog.FileName); } } #endregion #region Save 실행시 처리하기 - Save_Executed(sender, e) /// <summary> /// Save 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Save_Executed(object sender, ExecutedRoutedEventArgs e) { if(filePath == null || filePath.Length == 0) { ShowSaveDialog(string.Empty); } else { SaveFile(filePath); } } #endregion #region Save As 실행시 처리하기 - SaveAs_Executed(sender, e) /// <summary> /// Save As 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void SaveAs_Executed(object sender, ExecutedRoutedEventArgs e) { ShowSaveDialog(filePath); } #endregion #region Exit 메뉴 항목 클릭시 처리하기 - exitMenuItem_Click(sender, e) /// <summary> /// Exit 메뉴 항목 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void exitMenuItem_Click(object sender, RoutedEventArgs e) { Close(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region File 메뉴 추가하기 - AddFileMenu(menu) /// <summary> /// File 메뉴 추가하기 /// </summary> /// <param name="menu">Menu 객체</param> private void AddFileMenu(Menu menu) { #region Field 메뉴 항목 MenuItem fileMenuItem = new MenuItem(); fileMenuItem.Header = "_File"; menu.Items.Add(fileMenuItem); #endregion #region New 메뉴 항목 MenuItem newMenuItem = new MenuItem(); newMenuItem.Header = "_New"; newMenuItem.Command = ApplicationCommands.New; fileMenuItem.Items.Add(newMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.New, New_Executed)); #endregion #region Open 메뉴 항목 MenuItem openMenuItem = new MenuItem(); openMenuItem.Header = "_Open..."; openMenuItem.Command = ApplicationCommands.Open; fileMenuItem.Items.Add(openMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, Open_Executed)); #endregion #region Save 메뉴 항목 MenuItem saveMenuItem = new MenuItem(); saveMenuItem.Header = "_Save"; saveMenuItem.Command = ApplicationCommands.Save; fileMenuItem.Items.Add(saveMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, Save_Executed)); #endregion #region Save As 메뉴 항목 MenuItem saveAsMenuItem = new MenuItem(); saveAsMenuItem.Header = "Save _As..."; saveAsMenuItem.Command = ApplicationCommands.SaveAs; fileMenuItem.Items.Add(saveAsMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.SaveAs, SaveAs_Executed)); #endregion fileMenuItem.Items.Add(new Separator()); AddPrintMenuItems(fileMenuItem); fileMenuItem.Items.Add(new Separator()); #region Exit 메뉴 항목 MenuItem exitMenuItem = new MenuItem(); exitMenuItem.Header = "E_xit"; exitMenuItem.Click += exitMenuItem_Click; fileMenuItem.Items.Add(exitMenuItem); #endregion } #endregion #region 저장 대화 상자 보여주기 - ShowSaveDialog(filePath) /// <summary> /// 저장 대화 상자 보여주기 /// </summary> /// <param name="filePath">파일 경로</param> /// <returns>처리 결과</returns> private bool ShowSaveDialog(string filePath) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = this.filter; saveFileDialog.FileName = filePath; if((bool)saveFileDialog.ShowDialog(this)) { SaveFile(saveFileDialog.FileName); return true; } return false; } #endregion #region 버리기 여부 조사하기 - CheckToTrash() /// <summary> /// 버리기 여부 조사하기 /// </summary> /// <returns>버리기 여부</returns> private bool CheckToTrash() { if(!isFileDirty) { return true; } MessageBoxResult messageBoxResult = MessageBox.Show ( "The text in the file " + filePath + " has changed\n\nDo you want to save the changes?", applicationTitle, MessageBoxButton.YesNoCancel, MessageBoxImage.Question, MessageBoxResult.Yes ); if(messageBoxResult == MessageBoxResult.Cancel) // 취소한 경우 { return false; } else if(messageBoxResult == MessageBoxResult.No) // 저장하지 않는 경우 { return true; } else // 저장하는 경우 { if(filePath != null && filePath.Length > 0) { return SaveFile(filePath); } return ShowSaveDialog(string.Empty); } } #endregion #region 파일 로드하기 - LoadFile(filePath) /// <summary> /// 파일 로드하기 /// </summary> /// <param name="filePath">파일 경로</param> private void LoadFile(string filePath) { try { textBox.Text = File.ReadAllText(filePath); } catch(Exception exception) { MessageBox.Show ( "Error on File Open: " + exception.Message, applicationTitle, MessageBoxButton.OK, MessageBoxImage.Asterisk ); return; } this.filePath = filePath; UpdateTitle(); textBox.SelectionStart = 0; textBox.SelectionLength = 0; isFileDirty = false; } #endregion #region 파일 저장하기 - SaveFile(filePath) /// <summary> /// 파일 저장하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <returns>처리 결과</returns> private bool SaveFile(string filePath) { try { File.WriteAllText(filePath, textBox.Text); } catch(Exception exception) { MessageBox.Show ( "Error on File Save" + exception.Message, applicationTitle, MessageBoxButton.OK, MessageBoxImage.Asterisk ); return false; } this.filePath = filePath; UpdateTitle(); isFileDirty = false; return true; } #endregion } } |
▶ MainWindow.Find.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 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace TestProject { /// <summary> /// 메인 윈도우 (Find) /// </summary> public partial class MainWindow { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 찾기 텍스트 /// </summary> private string findText = string.Empty; /// <summary> /// 대체 텍스트 /// </summary> private string replaceText = string.Empty; /// <summary> /// 문자열 비교 /// </summary> private StringComparison stringComparison = StringComparison.OrdinalIgnoreCase; /// <summary> /// 찾기 방향 /// </summary> private FindDirection findDirection = FindDirection.Down; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 찾기 실행시 처리하기 - Find_Executed(sender, e) /// <summary> /// 찾기 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Find_Executed(object sender, ExecutedRoutedEventArgs e) { FindDialog findDialog = new FindDialog(this); findDialog.FindText = this.findText; findDialog.MatchCase = this.stringComparison == StringComparison.Ordinal; findDialog.FindDirection = this.findDirection; findDialog.FindNext += findDialog_FindNext; findDialog.Show(); } #endregion #region 찾기 실행 가능 여부 조사하기 - FindCanExecute(sender, e) /// <summary> /// 찾기 실행 가능 여부 조사하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void FindCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = (this.textBox.Text.Length > 0 && OwnedWindows.Count == 0); } #endregion #region 다음 찾기 실행시 처리하기 - FindNext_Executed(sender, e) /// <summary> /// 다음 찾기 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void FindNext_Executed(object sender, ExecutedRoutedEventArgs e) { if(this.findText == null || this.findText.Length == 0) { Find_Executed(sender, e); } else { FindNext(); } } #endregion #region 다음 찾기 실행 가능 여부 조사하기 - FindNextCanExecute(sender, e) /// <summary> /// 다음 찾기 실행 가능 여부 조사하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void FindNextCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = (this.textBox.Text.Length > 0 && this.findText.Length > 0); } #endregion #region 대체 실행시 처리하기 - Replace_Executed(sender, e) /// <summary> /// 대체 실행시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Replace_Executed(object sender, ExecutedRoutedEventArgs e) { ReplaceDialog replaceDialog = new ReplaceDialog(this); replaceDialog.FindText = this.findText; replaceDialog.ReplaceText = this.replaceText; replaceDialog.MatchCase = this.stringComparison == StringComparison.Ordinal; replaceDialog.FindDirection = this.findDirection; replaceDialog.FindNext += findDialog_FindNext; replaceDialog.Replace += replaceDialog_Replace; replaceDialog.ReplaceAll += replaceDialog_ReplaceAll; replaceDialog.Show(); } #endregion #region 찾기 대화 상자 다음 찾기 처리하기 - findDialog_FindNext(sender, e) /// <summary> /// 찾기 대화 상자 다음 찾기 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void findDialog_FindNext(object sender, EventArgs e) { CommonDialog commonDialog = sender as CommonDialog; this.findText = commonDialog.FindText; this.stringComparison = commonDialog.MatchCase ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; this.findDirection = commonDialog.FindDirection; FindNext(); } #endregion #region 대체 대화 상자 대체시 처리하기 - pReplaceDialog_Replace(sender, e) /// <summary> /// 대체 대화 상자 대체시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void replaceDialog_Replace(object sender, EventArgs e) { ReplaceDialog replaceDialog = sender as ReplaceDialog; this.findText = replaceDialog.FindText; this.replaceText = replaceDialog.ReplaceText; this.stringComparison = replaceDialog.MatchCase ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; if(this.findText.Equals(this.textBox.SelectedText, this.stringComparison)) { this.textBox.SelectedText = this.replaceText; } FindNext(); } #endregion #region 대체 대화 상자 전체 대체시 처리하기 - replaceDialog_ReplaceAll(sender, e) /// <summary> /// 대체 대화 상자 전체 대체시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void replaceDialog_ReplaceAll(object sender, EventArgs e) { ReplaceDialog replaceDialog = sender as ReplaceDialog; string text = this.textBox.Text; this.findText = replaceDialog.FindText; this.replaceText = replaceDialog.ReplaceText; this.stringComparison = replaceDialog.MatchCase ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; int index = 0; while(index + this.findText.Length < text.Length) { index = text.IndexOf(this.findText, index, this.stringComparison); if(index != -1) { text = text.Remove(index, this.findText.Length); text = text.Insert(index, this.replaceText); index += this.replaceText.Length; } else { break; } } this.textBox.Text = text; } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region Find 메뉴 항목 추가하기 - AddFindMenuItems(editMenuItem) /// <summary> /// Find 메뉴 항목 추가하기 /// </summary> /// <param name="editMenuItem">Edit 메뉴 항목</param> private void AddFindMenuItems(MenuItem editMenuItem) { #region Find 메뉴 항목 MenuItem findMenuItem = new MenuItem(); findMenuItem.Header = "_Find..."; findMenuItem.Command = ApplicationCommands.Find; editMenuItem.Items.Add(findMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.Find, Find_Executed, FindCanExecute)); #endregion #region Find Next 메뉴 항목 InputGestureCollection inputGestureCollection = new InputGestureCollection(); inputGestureCollection.Add(new KeyGesture(Key.F3)); RoutedUICommand findNextRoutedUICommand = new RoutedUICommand("Find _Next", "FindNext", GetType(), inputGestureCollection); MenuItem findNextMenuItem = new MenuItem(); findNextMenuItem.Command = findNextRoutedUICommand; editMenuItem.Items.Add(findNextMenuItem); CommandBindings.Add(new CommandBinding(findNextRoutedUICommand, FindNext_Executed, FindNextCanExecute)); #endregion #region Replace 메뉴 항목 MenuItem replaceMenuItem = new MenuItem(); replaceMenuItem.Header = "_Replace..."; replaceMenuItem.Command = ApplicationCommands.Replace; editMenuItem.Items.Add(replaceMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.Replace, Replace_Executed, FindCanExecute)); #endregion } #endregion #region 다음 찾기 - FindNext() /// <summary> /// 다음 찾기 /// </summary> private void FindNext() { int startIndex; int findIndex; if(this.findDirection == FindDirection.Down) { startIndex = this.textBox.SelectionStart + this.textBox.SelectionLength; findIndex = this.textBox.Text.IndexOf(this.findText, startIndex, this.stringComparison); } else { startIndex = this.textBox.SelectionStart; findIndex = this.textBox.Text.LastIndexOf(this.findText, startIndex, this.stringComparison); } if(findIndex != -1) { this.textBox.Select(findIndex, this.findText.Length); this.textBox.Focus(); } else { MessageBox.Show ( "Cannot find \"" + this.findText + "\"", Title, MessageBoxButton.OK, MessageBoxImage.Information ); } } #endregion } } |
▶ MainWindow.Format.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 |
using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; namespace TestProject { /// <summary> /// 메인 윈도우 (Format) /// </summary> public partial class MainWindow { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region Font 메뉴 항목 클릭시 처리하기 - fontMenuItem_Click(sender, e) /// <summary> /// Font 메뉴 항목 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void fontMenuItem_Click(object sender, RoutedEventArgs e) { FontDialog fontDialog = new FontDialog(); fontDialog.Owner = this; fontDialog.Typeface = new Typeface ( this.textBox.FontFamily, this.textBox.FontStyle , this.textBox.FontWeight, this.textBox.FontStretch ); fontDialog.FaceSize = this.textBox.FontSize; if(fontDialog.ShowDialog().GetValueOrDefault()) { this.textBox.FontFamily = fontDialog.Typeface.FontFamily; this.textBox.FontSize = fontDialog.FaceSize; this.textBox.FontStyle = fontDialog.Typeface.Style; this.textBox.FontWeight = fontDialog.Typeface.Weight; this.textBox.FontStretch = fontDialog.Typeface.Stretch; } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region Format 메뉴 추가하기 - AddFormatMenu(menu) /// <summary> /// Format 메뉴 추가하기 /// </summary> /// <param name="menu">Menu 객체</param> private void AddFormatMenu(Menu menu) { #region Format 메뉴 항목 MenuItem formatMenuItem = new MenuItem(); formatMenuItem.Header = "F_ormat"; menu.Items.Add(formatMenuItem); #endregion #region Word-Wrap 메뉴 항목 WordWrapMenuItem wordWrapMenuItem = new WordWrapMenuItem(); formatMenuItem.Items.Add(wordWrapMenuItem); Binding binding = new Binding(); binding.Path = new PropertyPath(TextBox.TextWrappingProperty); binding.Source = textBox; binding.Mode = BindingMode.TwoWay; wordWrapMenuItem.SetBinding(WordWrapMenuItem.WordWrapProperty, binding); #endregion #region Font 메뉴 항목 MenuItem fontMenuItem = new MenuItem(); fontMenuItem.Header = "_Font..."; fontMenuItem.Click += fontMenuItem_Click; formatMenuItem.Items.Add(fontMenuItem); #endregion } #endregion } } |
▶ MainWindow.Help.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 |
using System.Windows; using System.Windows.Controls; namespace TestProject { /// <summary> /// 메인 윈도우 (Help) /// </summary> public partial class MainWindow { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region About 메뉴 항목 클릭시 처리하기 - aboutMenuItem_Click(sender, e) /// <summary> /// About 메뉴 항목 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void aboutMenuItem_Click(object sender, RoutedEventArgs e) { AboutDialog aboutDialog = new AboutDialog(this); aboutDialog.ShowDialog(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region Help 메뉴 추가하기 - AddHelpMenu(menu) /// <summary> /// Help 메뉴 추가하기 /// </summary> /// <param name="menu">Menu 객체</param> private void AddHelpMenu(Menu menu) { #region Help 메뉴 항목 MenuItem helpMenuItem = new MenuItem(); helpMenuItem.Header = "_Help"; helpMenuItem.SubmenuOpened += viewMenuItem_SubmenuOpened; menu.Items.Add(helpMenuItem); #endregion #region About 메뉴 항목 MenuItem aboutMenuItem = new MenuItem(); aboutMenuItem.Header = "_About " + applicationTitle + "..."; aboutMenuItem.Click += aboutMenuItem_Click; helpMenuItem.Items.Add(aboutMenuItem); #endregion } #endregion } } |
▶ MainWindow.Print.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 |
using System.Printing; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace TestProject { /// <summary> /// 메인 윈도우 (Print) /// </summary> public partial class MainWindow : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 프린트 큐 /// </summary> private PrintQueue printQueue; /// <summary> /// 프린트 티켓 /// </summary> private PrintTicket printTicket; /// <summary> /// 마진 두께 /// </summary> private Thickness marginThickness = new Thickness(96); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region Setup 메뉴 항목 클릭시 처리하기 - setupMenuItem_Click(sender, e) /// <summary> /// Setup 메뉴 항목 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void setupMenuItem_Click(object sender, RoutedEventArgs e) { PageMarginDialog pageMarginDialog = new PageMarginDialog(); pageMarginDialog.Owner = this; pageMarginDialog.PageMargin = this.marginThickness; if(pageMarginDialog.ShowDialog().GetValueOrDefault()) { this.marginThickness = pageMarginDialog.PageMargin; } } #endregion #region Print 메뉴 항목 클릭시 처리하기 - Print_Executed(sender, e) /// <summary> /// Print 메뉴 항목 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void Print_Executed(object sender, ExecutedRoutedEventArgs e) { PrintDialog printDialog = new PrintDialog(); if(this.printQueue != null) { printDialog.PrintQueue = this.printQueue; } if(this.printTicket != null) { printDialog.PrintTicket = this.printTicket; } if(printDialog.ShowDialog().GetValueOrDefault()) { this.printQueue = printDialog.PrintQueue; this.printTicket = printDialog.PrintTicket; PlainTextDocumentPaginator plainTextDocumentPaginator = new PlainTextDocumentPaginator(); plainTextDocumentPaginator.PrintTicket = this.printTicket; plainTextDocumentPaginator.Text = this.textBox.Text; plainTextDocumentPaginator.HeaderText = filePath; plainTextDocumentPaginator.Typeface = new Typeface ( textBox.FontFamily, textBox.FontStyle, textBox.FontWeight, textBox.FontStretch ); plainTextDocumentPaginator.EMSize = this.textBox.FontSize; plainTextDocumentPaginator.TextWrapping = this.textBox.TextWrapping; plainTextDocumentPaginator.Margins = this.marginThickness; plainTextDocumentPaginator.PageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight); printDialog.PrintDocument(plainTextDocumentPaginator, Title); } } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region Print 메뉴 항목 추가하기 - AddPrintMenuItems(fileMenuItem) /// <summary> /// Print 메뉴 항목 추가하기 /// </summary> /// <param name="fileMenuItem">File 메뉴 항목</param> private void AddPrintMenuItems(MenuItem fileMenuItem) { #region Setup 메뉴 항목 MenuItem setupMenuItem = new MenuItem(); setupMenuItem.Header = "Page Set_up..."; setupMenuItem.Click += setupMenuItem_Click; fileMenuItem.Items.Add(setupMenuItem); #endregion #region Print 메뉴 항목 MenuItem printMenuItem = new MenuItem(); printMenuItem.Header = "_Print..."; printMenuItem.Command = ApplicationCommands.Print; fileMenuItem.Items.Add(printMenuItem); CommandBindings.Add(new CommandBinding(ApplicationCommands.Print, Print_Executed)); #endregion } #endregion } } |
▶ MainWindow.View.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 |
using System.Windows; using System.Windows.Controls; namespace TestProject { /// <summary> /// 메인 윈도우 (View) /// </summary> public partial class MainWindow { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// Status Bar 메뉴 항목 /// </summary> private MenuItem statusBarMenuItem; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region View 메뉴 항목 하위 메뉴 오픈시 처리하기 - viewMenuItem_SubmenuOpened(sender, e) /// <summary> /// View 메뉴 항목 하위 메뉴 오픈시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void viewMenuItem_SubmenuOpened(object sender, RoutedEventArgs e) { this.statusBarMenuItem.IsChecked = (statusBar.Visibility == Visibility.Visible); } #endregion #region Status Bar 메뉴 항목 체크시 처리하기 - statusBarMenuItem_Checked(sender, e) /// <summary> /// Status Bar 메뉴 항목 체크시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void statusBarMenuItem_Checked(object sender, RoutedEventArgs e) { MenuItem menuItem = sender as MenuItem; this.statusBar.Visibility = menuItem.IsChecked ? Visibility.Visible : Visibility.Collapsed; } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region View 메뉴 추가하기 - AddViewMenu(menu) /// <summary> /// View 메뉴 추가하기 /// </summary> /// <param name="menu">Menu 객체</param> private void AddViewMenu(Menu menu) { #region View 메뉴 항목 MenuItem viewMenuItem = new MenuItem(); viewMenuItem.Header = "_View"; viewMenuItem.SubmenuOpened += viewMenuItem_SubmenuOpened; menu.Items.Add(viewMenuItem); #endregion #region Status Bar 메뉴 항목 this.statusBarMenuItem = new MenuItem(); this.statusBarMenuItem.Header = "_Status Bar"; this.statusBarMenuItem.IsCheckable = true; this.statusBarMenuItem.Checked += this.statusBarMenuItem_Checked; this.statusBarMenuItem.Unchecked += this.statusBarMenuItem_Checked; viewMenuItem.Items.Add(this.statusBarMenuItem); #endregion } #endregion } } |
▶ NotepadCloneSetting.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 |
using System; using System.IO; using System.Windows; using System.Xml.Serialization; namespace TestProject { /// <summary> /// 노트패드 클론 설정 /// </summary> public class NotepadCloneSetting { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 윈도우 상태 /// </summary> public WindowState WindowState = WindowState.Normal; /// <summary> /// 복구 영역 /// </summary> public Rect RestoreBounds = Rect.Empty; /// <summary> /// 텍스트 랩핑 /// </summary> public TextWrapping TextWrapping = TextWrapping.NoWrap; /// <summary> /// 폰트 패밀리 /// </summary> public string FontFamily = ""; /// <summary> /// 폰트 스타일 /// </summary> public string FontStyle = new FontStyleConverter().ConvertToString(FontStyles.Normal); /// <summary> /// 폰트 가중치 /// </summary> public string FontWeight = new FontWeightConverter().ConvertToString(FontWeights.Normal); /// <summary> /// 폰트 확장 /// </summary> public string FontStretch = new FontStretchConverter().ConvertToString(FontStretches.Normal); /// <summary> /// 폰트 크기 /// </summary> public double FontSize = 11; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 저장하기 - Save(filePath) /// <summary> /// 저장하기 /// </summary> /// <param name="filePath">파일 경로</param> /// <returns>처리 결과</returns> public virtual bool Save(string filePath) { try { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); StreamWriter streamWriter = new StreamWriter(filePath); XmlSerializer xmlSerializer = new XmlSerializer(GetType()); xmlSerializer.Serialize(streamWriter, this); streamWriter.Close(); } catch { return false; } return true; } #endregion #region 로드하기 - Load(objectType, filePath) /// <summary> /// 로드하기 /// </summary> /// <param name="objectType">객체 타입</param> /// <param name="filePath">파일 경로</param> /// <returns>객체</returns> public static object Load(Type objectType, string filePath) { StreamReader streamReader; object targetObject; XmlSerializer xmlSerializer = new XmlSerializer(objectType); try { streamReader = new StreamReader(filePath); targetObject = xmlSerializer.Deserialize(streamReader); streamReader.Close(); } catch { targetObject = objectType.GetConstructor(Type.EmptyTypes).Invoke(null); } return targetObject; } #endregion } } |
▶ PageMarginDialog.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 |
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; namespace TestProject { /// <summary> /// 페이지 마진 대화 상자 /// </summary> public class PageMarginDialog : Window { //////////////////////////////////////////////////////////////////////////////////////////////////// Declaration ////////////////////////////////////////////////////////////////////////////////////////// Private #region Enumeration /// <summary> /// 측면 타입 /// </summary> private enum SideType { /// <summary> /// 왼쪽 /// </summary> Left, /// <summary> /// 오른쪽 /// </summary> Right, /// <summary> /// 위쪽 /// </summary> Top, /// <summary> /// 아래쪽 /// </summary> Bottom } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 텍스트 블럭 배열 /// </summary> private TextBox[] textBoxArray = new TextBox[4]; /// <summary> /// OK 버튼 /// </summary> private Button okButton; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 페이지 마진 - PageMargin /// <summary> /// 페이지 마진 /// </summary> public Thickness PageMargin { set { this.textBoxArray[(int)SideType.Left ].Text = (value.Left / 96d).ToString("F3"); this.textBoxArray[(int)SideType.Right ].Text = (value.Right / 96d).ToString("F3"); this.textBoxArray[(int)SideType.Top ].Text = (value.Top / 96d).ToString("F3"); this.textBoxArray[(int)SideType.Bottom].Text = (value.Bottom / 96d).ToString("F3"); } get { return new Thickness ( Double.Parse(this.textBoxArray[(int)SideType.Left ].Text) * 96d, Double.Parse(this.textBoxArray[(int)SideType.Right ].Text) * 96d, Double.Parse(this.textBoxArray[(int)SideType.Top ].Text) * 96d, Double.Parse(this.textBoxArray[(int)SideType.Bottom].Text) * 96d ); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - PageMarginDialog() /// <summary> /// 생성자 /// </summary> public PageMarginDialog() { Title = "Page Setting"; ShowInTaskbar = false; WindowStyle = WindowStyle.ToolWindow; WindowStartupLocation = WindowStartupLocation.CenterOwner; SizeToContent = SizeToContent.WidthAndHeight; ResizeMode = ResizeMode.NoResize; FontFamily = new FontFamily("나눔고딕코딩"); FontSize = 16; StackPanel stackPanel = new StackPanel(); Content = stackPanel; GroupBox groupBox = new GroupBox(); groupBox.Header = "Margins (inch)"; groupBox.Margin = new Thickness(12); stackPanel.Children.Add(groupBox); Grid grid = new Grid(); grid.Margin = new Thickness(6); groupBox.Content = grid; for(int i = 0 ; i < 2; i ++) { RowDefinition rowDefinition = new RowDefinition(); rowDefinition.Height = GridLength.Auto; grid.RowDefinitions.Add(rowDefinition); } for(int i = 0; i < 4; i++) { ColumnDefinition columnDefinition = new ColumnDefinition(); columnDefinition.Width = GridLength.Auto; grid.ColumnDefinitions.Add(columnDefinition); } for(int i = 0; i < 4; i++) { Label label = new Label(); label.Content = "_" + Enum.GetName(typeof(SideType), i) + " :"; label.Margin = new Thickness(6); label.VerticalAlignment = VerticalAlignment.Center; grid.Children.Add(label); Grid.SetRow (label, i / 2 ); Grid.SetColumn(label, 2 * (i % 2)); this.textBoxArray[i] = new TextBox(); this.textBoxArray[i].TextChanged += textBox_TextChanged; this.textBoxArray[i].MinWidth = 48; this.textBoxArray[i].Margin = new Thickness(6); grid.Children.Add(this.textBoxArray[i]); Grid.SetRow (this.textBoxArray[i], i / 2 ); Grid.SetColumn(this.textBoxArray[i], 2 * (i % 2) + 1); } UniformGrid uniformGrid = new UniformGrid(); uniformGrid.Rows = 1; uniformGrid.Columns = 2; stackPanel.Children.Add(uniformGrid); this.okButton = new Button(); this.okButton.Content = "_OK"; this.okButton.IsDefault = true; this.okButton.IsEnabled = false; this.okButton.MinWidth = 60; this.okButton.Margin = new Thickness(12); this.okButton.HorizontalAlignment = HorizontalAlignment.Center; this.okButton.Click += okButton_Click; uniformGrid.Children.Add(this.okButton); Button cancelButton = new Button(); cancelButton.Content = "_Cancel"; cancelButton.IsCancel = true; cancelButton.MinWidth = 60; cancelButton.Margin = new Thickness(12); cancelButton.HorizontalAlignment = HorizontalAlignment.Center; uniformGrid.Children.Add(cancelButton); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private #region 텍스트 박스 텍스트 변경시 처리하기 - textBox_TextChanged(sender, e) /// <summary> /// 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="pSender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void textBox_TextChanged(object pSender, TextChangedEventArgs e) { double result; this.okButton.IsEnabled = Double.TryParse(this.textBoxArray[(int)SideType.Left ].Text, out result) && Double.TryParse(this.textBoxArray[(int)SideType.Right ].Text, out result) && Double.TryParse(this.textBoxArray[(int)SideType.Top ].Text, out result) && Double.TryParse(this.textBoxArray[(int)SideType.Bottom].Text, out result); } #endregion #region OK 버튼 클릭시 처리하기 - okButton_Click(sender, e) /// <summary> /// OK 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void okButton_Click(object sender, RoutedEventArgs e) { DialogResult = true; } #endregion } } |
▶ PlainTextDocumentPaginator.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 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 |
using System.Collections.Generic; using System.Globalization; using System.IO; using System.Printing; using System.Windows; using System.Windows.Documents; using System.Windows.Media; namespace TestProject { /// <summary> /// 단순 텍스트 문서 페이지 지정자 /// </summary> public class PlainTextDocumentPaginator : DocumentPaginator { //////////////////////////////////////////////////////////////////////////////////////////////////// Declaration ////////////////////////////////////////////////////////////////////////////////////////// Private #region Class /// <summary> /// 프린트 라인 /// </summary> private class PrintLine { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 문자열 /// </summary> public string String; /// <summary> /// 플래그 /// </summary> public bool Flag; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - PrintLine(source, flag) /// <summary> /// 생성자 /// </summary> /// <param name="source">소스 문자열</param> /// <param name="flag">플래그</param> public PrintLine(string source, bool flag) { String = source; Flag = flag; } #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 중단 문자 배열 /// </summary> private char[] breakCharacterArray = new char[] { ' ', '-' }; /// <summary> /// 텍스트 /// </summary> private string text = string.Empty; /// <summary> /// 헤더 텍스트 /// </summary> private string headerText = null; /// <summary> /// 타입 페이스 /// </summary> private Typeface typeface = new Typeface(""); /// <summary> /// EM 크기 /// </summary> private double emSize = 11; /// <summary> /// 페이지 크기 /// </summary> private Size pageSize = new Size(8.5d * 96d, 11d * 96d); /// <summary> /// 최대 크기 /// </summary> private Size maximumSize = new Size(0, 0); /// <summary> /// 마진 두께 /// </summary> private Thickness marginThickness = new Thickness(96d); /// <summary> /// 프린트 티켓 /// </summary> private PrintTicket printTicket = new PrintTicket(); /// <summary> /// 텍스트 랩핑 /// </summary> private TextWrapping textWrapping = TextWrapping.Wrap; /// <summary> /// 문서 페이지 리스트 /// </summary> private List<DocumentPage> documentPageList; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 텍스트 - Text /// <summary> /// 텍스트 /// </summary> public string Text { set { this.text = value; } get { return this.text; } } #endregion #region 텍스트 랩핑 - TextWrapping /// <summary> /// 텍스트 랩핑 /// </summary> public TextWrapping TextWrapping { set { this.textWrapping = value; } get { return this.textWrapping; } } #endregion #region 마진 - Margins /// <summary> /// 마진 /// </summary> public Thickness Margins { set { this.marginThickness = value; } get { return this.marginThickness; } } #endregion #region 타입 페이스 - Typeface /// <summary> /// 타입 페이스 /// </summary> public Typeface Typeface { set { this.typeface = value; } get { return this.typeface; } } #endregion #region EM 크기 - EMSize /// <summary> /// EM 크기 /// </summary> public double EMSize { set { this.emSize = value; } get { return this.emSize; } } #endregion #region 프린트 티켓 - PrintTicket /// <summary> /// 프린트 티켓 /// </summary> public PrintTicket PrintTicket { set { this.printTicket = value; } get { return this.printTicket; } } #endregion #region 헤더 텍스트 - HeaderText /// <summary> /// 헤더 텍스트 /// </summary> public string HeaderText { set { this.headerText = value; } get { return this.headerText; } } #endregion #region 페이지 수 유효 여부 - IsPageCountValid /// <summary> /// 페이지 수 유효 여부 /// </summary> public override bool IsPageCountValid { get { if(this.documentPageList == null) { Format(); } return true; } } #endregion #region 페이지 수 - PageCount /// <summary> /// 페이지 수 /// </summary> public override int PageCount { get { if(this.documentPageList == null) { return 0; } return this.documentPageList.Count; } } #endregion #region 페이지 크기 - PageSize /// <summary> /// 페이지 크기 /// </summary> public override Size PageSize { set { this.pageSize = value; } get { return this.pageSize; } } #endregion #region 소스 - Source /// <summary> /// 소스 /// </summary> public override IDocumentPaginatorSource Source { get { return null; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 페이지 구하기 - GetPage(pageNumber) /// <summary> /// 페이지 구하기 /// </summary> /// <param name="pageNumber">페이지 번호</param> /// <returns>DocumentPage 객체</returns> public override DocumentPage GetPage(int pageNumber) { return this.documentPageList[pageNumber]; } #endregion #region FormattedText 객체 구하기 - GetFormattedText(text) /// <summary> /// FormattedText 객체 구하기 /// </summary> /// <param name="text">테스트</param> /// <returns>FormattedText 객체</returns> private FormattedText GetFormattedText(string text) { return new FormattedText ( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, this.typeface, this.emSize, Brushes.Black ); } #endregion #region 라인 처리하기 - ProcessLine(sourceLine, printableWidth, printLineList) /// <summary> /// 라인 처리하기 /// </summary> /// <param name="sourceLine">소스 라인</param> /// <param name="printableWidth">인쇄 가능한 너비</param> /// <param name="printLineList">프린트 라인 리스트</param> private void ProcessLine(string sourceLine, double printableWidth, List<PrintLine> printLineList) { sourceLine = sourceLine.TrimEnd(' '); if(TextWrapping == TextWrapping.NoWrap) { #region TextWrapping.NoWrap do { int length = sourceLine.Length; while(GetFormattedText(sourceLine.Substring(0, length)).Width > printableWidth) { length--; } printLineList.Add(new PrintLine(sourceLine.Substring(0, length), length < sourceLine.Length)); sourceLine = sourceLine.Substring(length); } while(sourceLine.Length > 0); #endregion } else { #region TextWrapping.Wrap, TextWrapping.WrapWithOverflow do { int length = sourceLine.Length; bool flag = false; while(GetFormattedText(sourceLine.Substring(0, length)).Width > printableWidth) { int index = sourceLine.LastIndexOfAny(this.breakCharacterArray, length - 2); if(index != -1) { length = index + 1; } else { index = sourceLine.IndexOfAny(this.breakCharacterArray); if(index != -1) { length = index + 1; } if(TextWrapping == TextWrapping.Wrap) { while(GetFormattedText(sourceLine.Substring(0, length)).Width > printableWidth) { length--; } flag = true; } break; } } printLineList.Add(new PrintLine(sourceLine.Substring(0, length), flag)); sourceLine = sourceLine.Substring(length); } while(sourceLine.Length > 0); #endregion } } #endregion #region 포맷하기 - Format() /// <summary> /// 포맷하기 /// </summary> private void Format() { List<PrintLine> printLineList = new List<PrintLine>(); FormattedText sampleFormattedText = GetFormattedText("W"); double printableWidth = PageSize.Width - Margins.Left - Margins.Right; if(printableWidth < sampleFormattedText.Width) { return; } string sourceLine; Pen pen = new Pen(Brushes.Black, 2); StringReader stringReader = new StringReader(this.text); while(null != (sourceLine = stringReader.ReadLine())) { ProcessLine(sourceLine, printableWidth, printLineList); } stringReader.Close(); double lineHeight = sampleFormattedText.LineHeight + sampleFormattedText.Height; double printableHeight = PageSize.Height - Margins.Top - Margins.Bottom; int pageLineCount = (int)(printableHeight / lineHeight); if(pageLineCount < 1) { return; } int pageCount = (printLineList.Count + pageLineCount - 1) / pageLineCount; double startX = Margins.Left; double startY = Margins.Top; this.documentPageList = new List<DocumentPage>(); for(int page = 0, line = 0; page < pageCount; page++) { DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); if(HeaderText != null && HeaderText.Length > 0) { FormattedText formattedText = GetFormattedText(HeaderText); formattedText.SetFontWeight(FontWeights.Bold); Point textPoint = new Point(startX, startY - 2 * formattedText.Height); drawingContext.DrawText(formattedText, textPoint); } if(pageCount > 1) { FormattedText formattedText = GetFormattedText("Page " + (page + 1) + " of " + pageCount); formattedText.SetFontWeight(FontWeights.Bold); Point textPoint = new Point ( (PageSize.Width + Margins.Left - Margins.Right - formattedText.Width) / 2d, PageSize.Height - Margins.Bottom + formattedText.Height ); drawingContext.DrawText(formattedText, textPoint); } for(int i = 0; i < pageLineCount; i++, line++) { if(line == printLineList.Count) { break; } string lineString = printLineList[line].String; FormattedText lineFormattedText = GetFormattedText(lineString); Point textPoint = new Point(startX, startY + i * lineHeight); drawingContext.DrawText(lineFormattedText, textPoint); if(printLineList[line].Flag) { double x = startX + printableWidth + 6; double y = startY + i * lineHeight + lineFormattedText.Baseline; double length = this.typeface.CapsHeight * this.emSize; drawingContext.DrawLine(pen, new Point(x, y), new Point(x + length , y - length )); drawingContext.DrawLine(pen, new Point(x, y), new Point(x , y - length / 2d)); drawingContext.DrawLine(pen, new Point(x, y), new Point(x + length / 2d, y )); } } drawingContext.Close(); DocumentPage documentPage = new DocumentPage(drawingVisual); this.documentPageList.Add(documentPage); } stringReader.Close(); } #endregion } } |
▶ ReplaceDialog.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 |
using System.Windows; namespace TestProject { /// <summary> /// 대체 대화 상자 /// </summary> public class ReplaceDialog : CommonDialog { //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - ReplaceDialog(ownerWindow) /// <summary> /// 생성자 /// </summary> /// <param name="ownerWindow">소유자 윈도우</param> public ReplaceDialog(Window ownerWindow) : base(ownerWindow) { Title = "Replace"; this.findDirectionGroupBox.Visibility = Visibility.Hidden; } #endregion } } |
▶ TextLister.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 |
using System; using System.Windows.Controls; using System.Windows.Input; namespace TestProject { /// <summary> /// 텍스트 리스터 /// </summary> public class TextLister : ContentControl { //////////////////////////////////////////////////////////////////////////////////////////////////// Event ////////////////////////////////////////////////////////////////////////////////////////// Public #region 텍스트 변경시 - TextChanged /// <summary> /// 텍스트 변경시 /// </summary> public event TextChangedEventHandler TextChanged; #endregion #region 선택 변경시 - SelectionChanged /// <summary> /// 선택 변경시 /// </summary> public event EventHandler SelectionChanged; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 텍스트 박스 /// </summary> private TextBox textBox; /// <summary> /// 리스터 /// </summary> private Lister lister; /// <summary> /// 읽기 전용 여부 /// </summary> private bool isReadOnly; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 텍스트 - Text /// <summary> /// 텍스트 /// </summary> public string Text { set { this.textBox.Text = value; } get { return this.textBox.Text; } } #endregion #region 읽기 전용 여부 - IsReadOnly /// <summary> /// 읽기 전용 여부 /// </summary> public bool IsReadOnly { set { this.isReadOnly = value; } get { return this.isReadOnly; } } #endregion #region 선택 인덱스 - SelectedIndex /// <summary> /// 선택 인덱스 /// </summary> public int SelectedIndex { set { this.lister.SelectedIndex = value; if(this.lister.SelectedIndex == -1) { this.textBox.Text = string.Empty; } else { this.textBox.Text = this.lister.SelectedItem.ToString(); } } get { return this.lister.SelectedIndex; } } #endregion #region 선택 항목 - SelectedItem /// <summary> /// 선택 항목 /// </summary> public object SelectedItem { set { this.lister.SelectedItem = value; if(this.lister.SelectedItem != null) { this.textBox.Text = this.lister.SelectedItem.ToString(); } else { this.textBox.Text = ""; } } get { return this.lister.SelectedItem; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - TextLister() /// <summary> /// 생성자 /// </summary> public TextLister() { DockPanel dockPanel = new DockPanel(); Content = dockPanel; this.textBox = new TextBox(); this.textBox.TextChanged += textBox_TextChanged; dockPanel.Children.Add(this.textBox); DockPanel.SetDock(this.textBox, Dock.Top); this.lister = new Lister(); this.lister.SelectionChanged += lister_SelectionChanged; dockPanel.Children.Add(this.lister); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 추가하기 - Add(item) /// <summary> /// 추가하기 /// </summary> /// <param name="item">항목</param> public void Add(object item) { this.lister.Add(item); } #endregion #region 삽입하기 - Insert(index, item) /// <summary> /// 삽입하기 /// </summary> /// <param name="index">인덱스</param> /// <param name="item">항목</param> public void Insert(int index, object item) { this.lister.Insert(index, item); } #endregion #region 지우기 - Clear() /// <summary> /// 지우기 /// </summary> public void Clear() { this.lister.Clear(); } #endregion #region 포함 여부 구하기 - Contains(item) /// <summary> /// 포함 여부 구하기 /// </summary> /// <param name="item">항목</param> /// <returns>포함 여부</returns> public bool Contains(object item) { return this.lister.Contains(item); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 마우스 다운시 처리하기 - OnMouseDown(e) /// <summary> /// 마우스 다운시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); Focus(); } #endregion #region 키보드 포커스 획득시 처리하기 - OnGotKeyboardFocus(e) /// <summary> /// 키보드 포커스 획득시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnGotKeyboardFocus(e); if(e.NewFocus == this) { this.textBox.Focus(); if(SelectedIndex == -1 && this.lister.Count > 0) { SelectedIndex = 0; } } } #endregion #region 프리뷰 텍스트 입력시 처리하기 - OnPreviewTextInput(e) /// <summary> /// 프리뷰 텍스트 입력시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnPreviewTextInput(TextCompositionEventArgs e) { base.OnPreviewTextInput(e); if(IsReadOnly) { this.lister.GoToLetter(e.Text[0]); e.Handled = true; } } #endregion #region 프리뷰 키 다운시 처리하기 - OnPreviewKeyDown(e) /// <summary> /// 프리뷰 키 다운시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnPreviewKeyDown(KeyEventArgs e) { base.OnPreviewKeyDown(e); if(SelectedIndex == -1) { return; } switch(e.Key) { case Key.Home : if(this.lister.Count > 0) { SelectedIndex = 0; } break; case Key.End : if(this.lister.Count > 0) { SelectedIndex = this.lister.Count - 1; } break; case Key.Up : if(SelectedIndex > 0) { SelectedIndex--; } break; case Key.Down : if(SelectedIndex < this.lister.Count - 1) { SelectedIndex++; } break; case Key.PageUp : this.lister.PageUp(); break; case Key.PageDown : this.lister.PageDown(); break; default : return; } e.Handled = true; } #endregion #region 선택 변경시 처리하기 - OnSelectionChanged(e) /// <summary> /// 선택 변경시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected virtual void OnSelectionChanged(EventArgs e) { if(SelectionChanged != null) { SelectionChanged(this, e); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 텍스트 박스 텍스트 변경시 처리하기 - textBox_TextChanged(sender, e) /// <summary> /// 텍스트 박스 텍스트 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void textBox_TextChanged(object sender, TextChangedEventArgs e) { if(TextChanged != null) { TextChanged(this, e); } } #endregion #region 리스터 선택 변경시 처리하기 - lister_SelectionChanged(sender, e) /// <summary> /// 리스터 선택 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void lister_SelectionChanged(object sender, EventArgs e) { if(SelectedIndex == -1) { this.textBox.Text = string.Empty; } else { this.textBox.Text = this.lister.SelectedItem.ToString(); } OnSelectionChanged(e); } #endregion } } |
▶ WordWrapMenuItem.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 |
using System.Windows; using System.Windows.Controls; namespace TestProject { /// <summary> /// 단어 랩핑 메뉴 항목 /// </summary> public class WordWrapMenuItem : MenuItem { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 단어 랩핑 /// </summary> public static DependencyProperty WordWrapProperty = DependencyProperty.Register ( "WordWrap", typeof(TextWrapping), typeof(WordWrapMenuItem) ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 단어 랩핑 - WordWrap /// <summary> /// 단어 랩핑 /// </summary> public TextWrapping WordWrap { set { SetValue(WordWrapProperty, value); } get { return (TextWrapping)GetValue(WordWrapProperty); } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - WordWrapMenuItem() /// <summary> /// 생성자 /// </summary> public WordWrapMenuItem() { Header = "_Word Wrap"; #region No Wrap 메뉴 항목 MenuItem noWrapMenuItem = new MenuItem(); noWrapMenuItem.Header = "_No Wrap"; noWrapMenuItem.Tag = TextWrapping.NoWrap; noWrapMenuItem.Click += menuItem_Click; Items.Add(noWrapMenuItem); #endregion #region Wrap 메뉴 항목 MenuItem wrapMenuItem = new MenuItem(); wrapMenuItem.Header = "_Wrap"; wrapMenuItem.Tag = TextWrapping.Wrap; wrapMenuItem.Click += menuItem_Click; Items.Add(wrapMenuItem); #endregion #region Wrap with Overflow 메뉴 항목 MenuItem wrapWithOverflowMenuItem = new MenuItem(); wrapWithOverflowMenuItem.Header = "Wrap with _Overflow"; wrapWithOverflowMenuItem.Tag = TextWrapping.WrapWithOverflow; wrapWithOverflowMenuItem.Click += menuItem_Click; Items.Add(wrapWithOverflowMenuItem); #endregion } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 하위 메뉴 오픈시 처리하기 - OnSubmenuOpened(e) /// <summary> /// 하위 메뉴 오픈시 처리하기 /// </summary> /// <param name="e">이벤트 인자</param> protected override void OnSubmenuOpened(RoutedEventArgs e) { base.OnSubmenuOpened(e); foreach(MenuItem menuItem in Items) { menuItem.IsChecked = ((TextWrapping)menuItem.Tag == WordWrap); } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 메뉴 항목 클릭시 처리하기 - menuItem_Click(sender, e) /// <summary> /// 메뉴 항목 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void menuItem_Click(object sender, RoutedEventArgs e) { WordWrap = (TextWrapping)(e.Source as MenuItem).Tag; } #endregion } } |