using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Provider;
using Windows.Storage.Streams;
using Windows.UI;
using Windows.UI.Popups;
using WinRT.Interop;
using Microsoft.UI;
using Microsoft.UI.Text;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Shapes;
namespace TestProject
{
/// <summary>
/// 메인 페이지
/// </summary>
public sealed partial class MainPage : Page
{
//////////////////////////////////////////////////////////////////////////////////////////////////// Import
////////////////////////////////////////////////////////////////////////////////////////// Static
//////////////////////////////////////////////////////////////////////////////// Private
#region 활성 윈도우 구하기 - GetActiveWindow()
/// <summary>
/// 활성 윈도우 구하기
/// </summary>
/// <returns></returns>
[DllImport("user32", ExactSpelling = true, CharSet = CharSet.Auto, PreserveSig = true, SetLastError = false)]
private static extern IntPtr GetActiveWindow();
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////// Field
////////////////////////////////////////////////////////////////////////////////////////// Private
#region Field
/// <summary>
/// 현재 색상
/// </summary>
private Color currentColor = Colors.Green;
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
////////////////////////////////////////////////////////////////////////////////////////// Public
#region 생성자 - MainPage()
/// <summary>
/// 생성자
/// </summary>
public MainPage()
{
InitializeComponent();
this.openFileButton.Click += openFileButton_Click;
this.saveFileButton.Click += saveFileButton_Click;
this.boldButton.Click += boldButton_Click;
this.italicButton.Click += italicButton_Click;
this.redColorButton.Click += colorButton_Click;
this.orangeColorButton.Click += colorButton_Click;
this.yellowColorButton.Click += colorButton_Click;
this.greenColorButton.Click += colorButton_Click;
this.blueColorButton.Click += colorButton_Click;
this.indigoColorButton.Click += colorButton_Click;
this.violetColorButton.Click += colorButton_Click;
this.grayColorButton.Click += colorButton_Click;
this.richEditBox.GotFocus += richEditBox_GotFocus;
this.richEditBox.TextChanged += richEditBox_TextChanged;
this.richEditBox.Document.GetDefaultCharacterFormat().ForegroundColor = Colors.Green;
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////// Method
////////////////////////////////////////////////////////////////////////////////////////// Private
//////////////////////////////////////////////////////////////////////////////// Event
#region Open file 버튼 클릭시 처리하기 - openFileButton_Click(sender, e)
/// <summary>
/// Open file 버튼 클릭시 처리하기
/// </summary>
/// <param name="sender">이벤트 발생자</param>
/// <param name="e">이벤트 인자</param>
private async void openFileButton_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
fileOpenPicker.FileTypeFilter.Add(".rtf");
if(Window.Current == null)
{
IntPtr windowHandle = GetActiveWindow();
InitializeWithWindow.Initialize(fileOpenPicker, windowHandle);
}
StorageFile storageFile = await fileOpenPicker.PickSingleFileAsync();
if(storageFile != null)
{
using(IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.Read))
{
this.richEditBox.Document.LoadFromStream(TextSetOptions.FormatRtf, stream);
}
}
}
#endregion
#region Save file 버튼 클릭시 처리하기 - saveFileButton_Click(sender, e)
/// <summary>
/// Save file 버튼 클릭시 처리하기
/// </summary>
/// <param name="sender">이벤트 발생자</param>
/// <param name="e">이벤트 인자</param>
private async void saveFileButton_Click(object sender, RoutedEventArgs e)
{
FileSavePicker fileSavePicker = new FileSavePicker
{
SuggestedStartLocation = PickerLocationId.DocumentsLibrary
};
fileSavePicker.FileTypeChoices.Add("Rich Text", new List<string>() { ".rtf" });
fileSavePicker.SuggestedFileName = "New Document";
if(Window.Current == null)
{
IntPtr windowHandle = GetActiveWindow();
InitializeWithWindow.Initialize(fileSavePicker, windowHandle);
}
StorageFile storageFile = await fileSavePicker.PickSaveFileAsync();
if(storageFile != null)
{
CachedFileManager.DeferUpdates(storageFile);
using(IRandomAccessStream stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
this.richEditBox.Document.SaveToStream(TextGetOptions.FormatRtf, stream);
}
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(storageFile);
if(status != FileUpdateStatus.Complete)
{
MessageDialog messageDialog = new MessageDialog("File " + storageFile.Name + " couldn't be saved.");
await messageDialog.ShowAsync();
}
}
}
#endregion
#region Bold 버튼 클릭시 처리하기 - boldButton_Click(sender, e)
/// <summary>
/// Bold 버튼 클릭시 처리하기
/// </summary>
/// <param name="sender">이벤트 발생자</param>
/// <param name="e">이벤트 인자</param>
private void boldButton_Click(object sender, RoutedEventArgs e)
{
this.richEditBox.Document.Selection.CharacterFormat.Bold = FormatEffect.Toggle;
}
#endregion
#region Italic 버튼 클릭시 처리하기 - italicButton_Click(sender, e)
/// <summary>
/// Italic 버튼 클릭시 처리하기
/// </summary>
/// <param name="sender">이벤트 발생자</param>
/// <param name="e">이벤트 인자</param>
private void italicButton_Click(object sender, RoutedEventArgs e)
{
this.richEditBox.Document.Selection.CharacterFormat.Italic = FormatEffect.Toggle;
}
#endregion
#region 색상 버튼 클릭시 처리하기 - colorButton_Click(sender, e)
/// <summary>
/// 색상 버튼 클릭시 처리하기
/// </summary>
/// <param name="sender">이벤트 발생자</param>
/// <param name="e">이벤트 인자</param>
private void colorButton_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
Rectangle rectangle = button.Content as Rectangle;
Color color = (rectangle.Fill as SolidColorBrush).Color;
this.richEditBox.Document.Selection.CharacterFormat.ForegroundColor = color;
this.fontColorButton.Flyout.Hide();
this.richEditBox.Focus(FocusState.Keyboard);
this.currentColor = color;
}
#endregion
#region 리치 에디트 박스 포커스 획득시 처리하기 - richEditBox_GotFocus(sender, e)
/// <summary>
/// 리치 에디트 박스 포커스 획득시 처리하기
/// </summary>
/// <param name="sender">이벤트 발생자</param>
/// <param name="e">이벤트 인자</param>
private void richEditBox_GotFocus(object sender, RoutedEventArgs e)
{
this.richEditBox.Document.GetText(TextGetOptions.UseCrlf, out _);
ITextRange textRange = richEditBox.Document.GetRange(0, TextConstants.MaxUnitCount);
SolidColorBrush backgroundBrush = App.Current.Resources["TextControlBackgroundFocused"] as SolidColorBrush;
if(backgroundBrush != null)
{
textRange.CharacterFormat.BackgroundColor = backgroundBrush.Color;
}
}
#endregion
#region 리치 에디트 박스 텍스트 변경시 처리하기 - richEditBox_TextChanged(sender, e)
/// <summary>
/// 리치 에디트 박스 텍스트 변경시 처리하기
/// </summary>
/// <param name="sender">이벤트 발생자</param>
/// <param name="e">이벤트 인자</param>
private void richEditBox_TextChanged(object sender, RoutedEventArgs e)
{
if(this.richEditBox.Document.Selection.CharacterFormat.ForegroundColor != this.currentColor)
{
this.richEditBox.Document.Selection.CharacterFormat.ForegroundColor = this.currentColor;
}
}
#endregion
//////////////////////////////////////////////////////////////////////////////// Function
#region Find 텍스트 박스 하이라이트 설정하기 - SetFindTextBoxHighlight()
/// <summary>
/// Find 텍스트 박스 하이라이트 설정하기
/// </summary>
private void SetFindTextBoxHighlight()
{
ClearFindTextBoxHighlight();
Color highlightBackgroundColor = (Color)App.Current.Resources["SystemColorHighlightColor" ];
Color highlightForegroundColor = (Color)App.Current.Resources["SystemColorHighlightTextColor"];
string textToFind = this.findTextBox.Text;
if(textToFind != null)
{
ITextRange textRange = this.richEditBox.Document.GetRange(0, 0);
while(textRange.FindText(textToFind, TextConstants.MaxUnitCount, FindOptions.None) > 0)
{
textRange.CharacterFormat.BackgroundColor = highlightBackgroundColor;
textRange.CharacterFormat.ForegroundColor = highlightForegroundColor;
}
}
}
#endregion
#region Find 텍스트 박스 하이라이트 지우기 - ClearFindTextBoxHighlight()
/// <summary>
/// Find 텍스트 박스 하이라이트 지우기
/// </summary>
private void ClearFindTextBoxHighlight()
{
ITextRange textRange = this.richEditBox.Document.GetRange(0, TextConstants.MaxUnitCount);
SolidColorBrush defaultBackgroundBrush = this.richEditBox.Background as SolidColorBrush;
SolidColorBrush defaultForegroundBrush = this.richEditBox.Foreground as SolidColorBrush;
textRange.CharacterFormat.BackgroundColor = defaultBackgroundBrush.Color;
textRange.CharacterFormat.ForegroundColor = defaultForegroundBrush.Color;
}
#endregion
}
}