FormWordpad.cs

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.Win32;
using Word = Microsoft.Office.Interop.Word;

namespace DIYWordpad
{
    public partial class FormWordpad : Form
    {
        #region 自定义对象
        private FileInfo currentFile;
        private StringBuilder sbTitle, sbText;
        private ChineseLunisolarCalendar lunarCalendar;
        private readonly string tempFilePath, animals;
        #endregion

        #region AnimateWindow
        [DllImport("user32.dll", EntryPoint = "AnimateWindow")]
        private static extern bool AnimateWindow(IntPtr handle, int ms, int flags);
        #endregion

        public FormWordpad()
        {
            #region
            InitializeComponent();
            sbText = new StringBuilder();
            sbTitle = new StringBuilder("文档 - 写字板        ");
            lunarCalendar = new ChineseLunisolarCalendar(); // 中国阴阳历。
            tempFilePath = Path.GetTempFileName();
            animals = "鼠牛虎兔龙蛇马羊猴鸡狗猪";
            richText.AcceptsTab = true;                // Tab ~ Ctrl+Tab。
            richText.AllowDrop = true;                // 允许拖放操作。
            richText.DetectUrls = true;              // 自动设置 URL 链接格式。
            richText.EnableAutoDragDrop = true;     // 在文本、图片和其他数据上启用拖放操作。
            richText.HideSelection = false;        // 无焦点时,选定文本保持突出显示。
            richText.ShortcutsEnabled = true;     // 启用定义的快捷方式。
            richText.ShowSelectionMargin = true; // 显示选定内容的边距。
            richText.DragEnter += new DragEventHandler(richText_DragEnter);
            richText.DragDrop += new DragEventHandler(richText_DragDrop);
            var query = from kc in Enum.GetNames(typeof(KnownColor))
                        let bc = Color.FromName(kc)
                        where !bc.IsSystemColor && bc != Color.Transparent // 禁用系统颜色和透明颜色。
                        select (bc as object); // 装箱转换。
            colorComboBox.Items.AddRange(query.ToArray());
            colorComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
            colorComboBox.ComboBox.DrawMode = DrawMode.OwnerDrawFixed; // 用代码绘制控件中的所有元素,并且元素大小都相等。
            colorComboBox.ComboBox.DrawItem += new DrawItemEventHandler(colorComboBox_DrawItem);
            using (RegistryKey userKey = Application.UserAppDataRegistry)
            {
                colorComboBox.SelectedItem = Color.FromName(userKey.GetValue("BackColor") + "");
                foreach (string filePath in userKey.CreateSubKey("FileList").GetValueNames())
                {
                    fileListMenu.DropDownItems.Add(filePath).MouseUp += new MouseEventHandler(menuItem_MouseUp);
                }
            }
            #endregion
        }

        #region FormLoad
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            fontNameComboBox.ComboBox.DataSource = FontFamily.Families;
            fontNameComboBox.ComboBox.DisplayMember = "Name";
            fontNameComboBox.Text = richText.Font.Name;
            fontSizeComboBox.ComboBox.DataSource = new float[] { 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 48, 64, 72 };
            cultureComboBox.Sorted = true;
            cultureComboBox.Items.AddRange(CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures));
            cultureComboBox.ComboBox.DisplayMember = "DisplayName";
            cultureComboBox.SelectedItem = Application.CurrentCulture;
            languageComboBox.Sorted = true;
            languageComboBox.Items.AddRange(InputLanguage.InstalledInputLanguages.Cast<InputLanguage>().ToArray());
            languageComboBox.ComboBox.DisplayMember = "LayoutName";
            languageComboBox.SelectedItem = Application.CurrentInputLanguage;
            toolMenu.CheckOnClick = true;
            toolStrip.DataBindings.Add("Visible", toolMenu, "Checked");
            fontFormatMenu.CheckOnClick = true;
            formatStrip.DataBindings.Add("Visible", fontFormatMenu, "Checked");
            statusMenu.CheckOnClick = true;
            statusStrip.DataBindings.Add("Visible", statusMenu, "Checked");
            wordWrapMenu.CheckOnClick = true;
            richText.DataBindings.Add("WordWrap", wordWrapMenu, "Checked");
            topMostMenu.CheckOnClick = true;
            this.DataBindings.Add("TopMost", topMostMenu, "Checked");
            this.DataBindings.Add("BackColor", richText, "BackColor");
            AnimateWindow(this.Handle, 1000, 0x20010);
        }
        #endregion

        #region FormClosing
        private void exitMenu_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            if (richText.Modified)
            {
                string text = (currentFile == null) ? "文档" : Path.GetFileNameWithoutExtension(currentFile.Name);
                switch (MessageBox.Show(this, string.Format("文件 {0} 的内容已经改变。/n想保存文件吗?", text), "写字板", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
                {
                    case DialogResult.Yes:
                        if (currentFile == null)
                            saveAsMenu.PerformClick();
                        else
                            saveDropDown.ShowDropDown();
                        e.Cancel = true;
                        return;
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        return;
                }
            }
            File.Delete(tempFilePath); // 如果指定的文件不存在,则不引发异常。
            using (RegistryKey subKey = Application.UserAppDataRegistry)
            {
                subKey.SetValue("BackColor", richText.BackColor.Name);
            }
            AnimateWindow(this.Handle, 1000, 0x10010);
        }
        #endregion

        #region ModifiedOrFilter
        /// <summary>
        /// 用户是否修改了 RichTextBox 控件的内容。
        /// </summary>
        /// <returns></returns>
        private bool GetModified()
        {
            if (richText.Modified)
            {
                string text = (currentFile == null) ? "文档" : Path.GetFileNameWithoutExtension(currentFile.Name);
                if (MessageBox.Show(this, string.Format("文件 {0} 的内容已经改变。/n想保存文件吗?", text), "写字板", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (currentFile == null)
                        saveAsMenu.PerformClick();
                    else
                        saveDropDown.ShowDropDown();
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 设置文件名筛选器字符串。
        /// </summary>
        /// <param name="flag">打开文档 flag = true,打开图片 flag = false。</param>
        private void OpenFileToFilter(bool flag)
        {
            if (flag)
            {
                sbText.Append("ASP.NET File (*.aspx)|*.aspx|");
                sbText.Append("C# File (*.cs)|*.cs|");
                sbText.Append("CSS File (*.css)|*.css|");
                sbText.Append("JAVA File (*.java)|*.java|");
                sbText.Append("JavaScript File (*.js)|*.js|");
                sbText.Append("JSP File (*.jsp)|*.jsp|");
                sbText.Append("LOG File (*.log)|*.log|");
                sbText.Append("MHTML File (*.mht)|*.mht|");
                sbText.Append("RTF File (*.rtf)|*.rtf|");
                sbText.Append("SQL File (*.sql)|*.sql|");
                sbText.Append("TXT File (*.txt)|*.txt|");
                sbText.Append("Word File (*.doc;*.docx)|*.doc;*.docx|");
                sbText.Append("XML File (*.xml)|*.xml|");
                sbText.Append("XSD File (*.xsd)|*.xsd|");
                sbText.Append("AllFile (*.*)|*.*");
            }
            else
            {
                sbText.Append("ImageFormat (*.BMP;*.GIF;*.JPG;*.PNG)");
                sbText.Append("|*.bmp;*.gif;*.jpg;*.jpeg;*.png");
                sbText.Append("|AllImage (*.*)|*.*");
            }
            openFile.Multiselect = true; // 指示对话框允许选择多个文件。
            openFile.FileName = null;
            openFile.Filter = sbText.ToString();
            sbText.Capacity = sbText.Remove(0, sbText.Length).Length;
        }
        #endregion

        #region AccessFile
        private void recentMenu_Click(object sender, EventArgs e)
        {
            Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Recent));
        }

        private void menuItem_MouseUp(object sender, MouseEventArgs e)
        {
            ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
            switch (e.Button)
            {
                case MouseButtons.Left:
                    if (GetModified())
                        return;
                    if (File.Exists(menuItem.Text))
                    {
                        this.LoadFile(menuItem.Text);
                        foreach (ToolStripMenuItem item in fileListMenu.DropDownItems)
                        {
                            item.Checked = item.Equals(menuItem);
                        }
                    }
                    else
                        MessageBox.Show(this, string.Format("指定的文件 {0} 不存在。", menuItem.Text), "写字板", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    break;
                case MouseButtons.Right:
                    fileMenu.HideDropDown();
                    if (MessageBox.Show(this, string.Format("确实要删除 {0} 文件路径吗?", menuItem.Text), "确认删除项", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        fileListMenu.DropDownItems.Remove(menuItem);
                        using (RegistryKey subKey = Application.UserAppDataRegistry.CreateSubKey("FileList"))
                        {
                            subKey.DeleteValue(menuItem.Text, false); // false, 指定的值不存在时不引发异常。
                        }
                    }
                    break;
            }
        }

        private void fileClearMenu_Click(object sender, EventArgs e)
        {
            if (fileListMenu.HasDropDownItems)
            {
                fileListMenu.DropDownItems.Clear();
                using (RegistryKey subKey = Application.UserAppDataRegistry)
                {
                    if (subKey.OpenSubKey("FileList") != null)
                        subKey.DeleteSubKeyTree("FileList");
                }
            }
        }
        #endregion

        #region DragDropFile
        private void richText_DragEnter(object sender, DragEventArgs e)
        {
            richText.EnableAutoDragDrop = !(e.Data as DataObject).ContainsFileDropList();
        }

        private void richText_DragDrop(object sender, DragEventArgs e)
        {
            if (richText.EnableAutoDragDrop)
                return;
            string filePath = (e.Data as DataObject).GetFileDropList()[0];
            if ((File.GetAttributes(filePath) & FileAttributes.Directory) != 0)
                return;
            if (Regex.IsMatch(Path.GetExtension(filePath), @".(bmp|gif|jpg|png)", RegexOptions.IgnoreCase)) // 指定不区分大小写的匹配。
                using (Bitmap bmp = new Bitmap(filePath))
                {
                    IDataObject data = Clipboard.GetDataObject();
                    Clipboard.SetImage(bmp);
                    if (Clipboard.ContainsImage())
                        richText.Paste();
                    Clipboard.SetDataObject(data, true);
                }
            else
            {
                if (GetModified())
                    return;
                this.LoadFile(filePath);
                using (RegistryKey subKey = Application.UserAppDataRegistry.CreateSubKey("FileList"))
                {
                    subKey.SetValue(filePath, "");
                    if (fileListMenu.DropDownItems.Count < subKey.ValueCount) // 防止记录重复文件路径。
                        fileListMenu.DropDownItems.Add(filePath).MouseUp += new MouseEventHandler(menuItem_MouseUp);
                }
            }
            this.Activate(); // 激活窗体并给予它焦点。
        }
        #endregion

        #region NewFile
        private void newMenu_Click(object sender, EventArgs e)
        {
            if (GetModified())
                return;
            richText.Clear();
            sbTitle.Remove(0, sbTitle.Length);
            sbTitle.Capacity = sbTitle.Append("文档 - 写字板        ").Length;
            this.Text = null;
            this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
            saveMenu.Enabled = saveDropDown.Enabled = false;
            attributesMenu.Enabled = false;
            fileWatcher.EnableRaisingEvents = false; // 禁用监视文件。
            Environment.CurrentDirectory = Application.StartupPath;
            currentFile = null;
        }
        #endregion

        #region OpenFile
        private void openMenu_Click(object sender, EventArgs e)
        {
            if (GetModified())
                return;
            this.OpenFileToFilter(true);
            if (openFile.ShowDialog(this) == DialogResult.OK)
            {
                this.LoadFile(openFile.FileName);
                using (RegistryKey subKey = Application.UserAppDataRegistry.CreateSubKey("FileList"))
                {
                    foreach (string filePath in openFile.FileNames)
                    {
                        subKey.SetValue(filePath, "");
                        if (fileListMenu.DropDownItems.Count < subKey.ValueCount) // 防止记录重复文件路径。
                            fileListMenu.DropDownItems.Add(filePath).MouseUp += new MouseEventHandler(menuItem_MouseUp);
                    }
                }
            }
        }
        #endregion

        #region LoadFile
        /// <summary>
        /// filePath: 要加载到 RichTextBox 控件中的文件路径。
        /// </summary>
        /// <param name="filePath"></param>
        private void LoadFile(string filePath)
        {
            try
            {
                currentFile = new FileInfo(filePath);
                switch (currentFile.Extension.ToLowerInvariant())
                {
                    case ".rtf":
                        richText.LoadFile(filePath);
                        File.WriteAllBytes(tempFilePath, File.ReadAllBytes(filePath));
                        break;
                    case ".doc":
                    case ".docx":
                        Word.Application newWord = new Word.Application();
                        newWord.Visible = false;
                        object readOnly = true;
                        object fileName = filePath;
                        object missing = Type.Missing;
                        Word.Document doc = newWord.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                        fileName = tempFilePath;
                        object format = Word.WdSaveFormat.wdFormatRTF;
                        doc.SaveAs(ref fileName, ref format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                        doc.Close(ref missing, ref missing, ref missing);
                        newWord.Quit(ref missing, ref missing, ref missing);
                        newWord = null;
                        richText.LoadFile(tempFilePath);
                        break;
                    default:
                        richText.Text = File.ReadAllText(filePath, Encoding.Default);
                        File.WriteAllBytes(tempFilePath, File.ReadAllBytes(filePath));
                        break;
                }
                richText.SelectionStart = 1;
                sbTitle.Remove(0, sbTitle.Length);
                sbTitle.Append(currentFile.Name);
                if (currentFile.IsReadOnly)
                    sbTitle.Append(" 只读");
                if ((currentFile.Attributes & FileAttributes.Hidden) != 0) // 取交集。
                    sbTitle.Append(" 隐藏");
                sbTitle.Capacity = sbTitle.Append("        ").Length;
                this.Text = null;
                this.Icon = Icon.ExtractAssociatedIcon(filePath);
                saveMenu.Enabled = saveDropDown.Enabled = true;
                attributesMenu.Enabled = true;
                Environment.CurrentDirectory = currentFile.DirectoryName; // 设置当前工作目录。
                fileWatcher.Path = currentFile.DirectoryName; // 监视目录。
                fileWatcher.Filter = currentFile.Name;       // 监视文件。
                fileWatcher.EnableRaisingEvents = true;     // 启用监视。
            }
            catch (Exception se)
            {
                MessageBox.Show(this, se.Message, "写字板", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region SaveFile
        private void contextEncoding_Opening(object sender, CancelEventArgs e)
        {
            if (e.Cancel = !contextEncoding.OwnerItem.Enabled)
                return;
            bool flag = (currentFile.Extension.ToLowerInvariant() != ".rtf");
            foreach (ToolStripMenuItem item in contextEncoding.Items)
            {
                item.Visible = item.Equals(cmsRTF) ^ flag;
            }
        }

        private void contextEncoding_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            currentFile.Refresh();
            if (currentFile.Exists)
            {
                if (currentFile.IsReadOnly)
                {
                    fileMenu.HideDropDown();
                    if (MessageBox.Show(this, string.Format("文件 {0} 的属性为只读。/n确实要保存吗?", currentFile.FullName), "写字板", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        return;
                }
                currentFile.Attributes = FileAttributes.Normal;
            }
            switch (contextEncoding.Items.IndexOf(e.ClickedItem))
            {
                case 0:
                    File.WriteAllLines(currentFile.FullName, richText.Lines, Encoding.Default);
                    break;
                case 1:
                    File.WriteAllLines(currentFile.FullName, richText.Lines, Encoding.GetEncoding("GB18030"));
                    break;
                case 2:
                    File.WriteAllLines(currentFile.FullName, richText.Lines, Encoding.UTF8);
                    break;
                case 3:
                    File.WriteAllLines(currentFile.FullName, richText.Lines, Encoding.Unicode);
                    break;
                case 4:
                    File.WriteAllLines(currentFile.FullName, richText.Lines, Encoding.BigEndianUnicode);
                    break;
                case 5:
                    richText.SaveFile(currentFile.FullName);
                    break;
            }
            foreach (ToolStripMenuItem item in contextEncoding.Items)
            {
                item.Checked = item.Equals(e.ClickedItem);
            }
            richText.Modified = false;
        }
        #endregion

        #region SaveAsFile
        private void saveAsMenu_Click(object sender, EventArgs e)
        {
            sbText.Append("ANSI|*.txt|");
            sbText.Append("GB18030|*.*|");
            sbText.Append("UTF-8|*.*|");
            sbText.Append("Unicode|*.*|");
            sbText.Append("Unicode Big-Endian|*.*|");
            sbText.Append("RTF|*.rtf");
            saveFile.OverwritePrompt = false; // 另存为对话框隐藏警告。
            saveFile.FileName = (currentFile == null) ? "文档" : currentFile.Name;
            saveFile.FilterIndex = 6;
            saveFile.Filter = sbText.ToString();
            sbText.Capacity = sbText.Remove(0, sbText.Length).Length;
            saveFile.ShowDialog(this);
        }

        private void saveFile_FileOk(object sender, CancelEventArgs e)
        {
            if (saveFile.FilterIndex == 6)
                saveFile.FileName = Path.ChangeExtension(saveFile.FileName, ".rtf");
            FileInfo info = new FileInfo(saveFile.FileName);
            if (info.Exists)
            {
                if (MessageBox.Show(this, string.Format("文件 {0} 已存在。/n要替换它吗?", info.FullName), "另存为", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    e.Cancel = true;
                    return;
                }
                info.Attributes = FileAttributes.Normal;
            }
            switch (saveFile.FilterIndex)
            {
                case 1:
                    File.WriteAllLines(info.FullName, richText.Lines, Encoding.Default);
                    break;
                case 2:
                    File.WriteAllLines(info.FullName, richText.Lines, Encoding.GetEncoding("GB18030"));
                    break;
                case 3:
                    File.WriteAllLines(info.FullName, richText.Lines, Encoding.UTF8);
                    break;
                case 4:
                    File.WriteAllLines(info.FullName, richText.Lines, Encoding.Unicode);
                    break;
                case 5:
                    File.WriteAllLines(info.FullName, richText.Lines, Encoding.BigEndianUnicode);
                    break;
                case 6:
                    richText.SaveFile(info.FullName);
                    break;
            }
            richText.Modified = false;
        }
        #endregion

        #region BackupFile
        private void backupFileMenu_Click(object sender, EventArgs e)
        {
            if (GetModified())
                return;
            if (File.Exists(tempFilePath))
            {
                try
                {
                    richText.LoadFile(tempFilePath);
                }
                catch
                {
                    richText.Text = File.ReadAllText(tempFilePath, Encoding.Default);
                }
                richText.SelectionStart = 1;
            }
            else
                MessageBox.Show(this, string.Format("备份文件 {0} 不存在。", tempFilePath), "写字板", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        #endregion

        #region PrintFile
        private void pageSetupMenu_Click(object sender, EventArgs e)
        {
            if (richText.TextLength < 1)
                return;
            try
            {
                pageSetup.Document = printDocument;
                pageSetup.ShowDialog(this);
            }
            catch (Exception se)
            {
                MessageBox.Show(this, se.Message, "写字板", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void printMenu_Click(object sender, EventArgs e)
        {
            if (richText.TextLength < 1)
                return;
            try
            {
                printDialog.Document = printDocument;
                if (printDialog.ShowDialog(this) == DialogResult.OK)
                {
                    sbText.Capacity = sbText.Append(richText.Text).Length;
                    printDocument.Print();
                }
            }
            catch (Exception se)
            {
                MessageBox.Show(this, se.Message, "写字板", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void printPreviewMenu_Click(object sender, EventArgs e)
        {
            if (richText.TextLength < 1)
                return;
            try
            {
                sbText.Capacity = sbText.Append(richText.Text).Length;
                printPreview.Document = printDocument;
                printPreview.WindowState = FormWindowState.Maximized;
                printPreview.ShowDialog(this);
            }
            catch (Exception se)
            {
                sbText.Capacity = sbText.Remove(0, sbText.Length).Length;
                MessageBox.Show(this, se.Message, "写字板", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            try
            {
                using (Graphics g = e.Graphics)
                {
                    int length, lines;
                    StringFormat format = StringFormat.GenericTypographic; // 获取一般的版式。
                    g.MeasureString(sbText.ToString(), richText.Font, e.MarginBounds.Size, format, out length, out lines);
                    g.DrawString(sbText.ToString(0, length), richText.Font, Brushes.Black, e.MarginBounds, format);
                    sbText.Capacity = sbText.Remove(0, length).Length;
                    e.HasMorePages = (sbText.Length > 0); // 打印附加页。
                }
            }
            catch (Exception se)
            {
                e.Cancel = true;
                sbText.Capacity = sbText.Remove(0, sbText.Length).Length;
                MessageBox.Show(this, se.Message, "写字板", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region FileSystemWatcher
        private void fileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            currentFile.Refresh();
            sbTitle.Remove(0, sbTitle.Length);
            sbTitle.Append(e.Name);
            if (currentFile.IsReadOnly)
                sbTitle.Append(" 只读");
            if ((currentFile.Attributes & FileAttributes.Hidden) != 0) // 取交集。
                sbTitle.Append(" 隐藏");
            sbTitle.Capacity = sbTitle.Append("        ").Length;
            this.Text = null;
            attributesMenu.Enabled = true;
        }

        private void fileWatcher_Renamed(object sender, RenamedEventArgs e)
        {
            currentFile = new FileInfo(e.FullPath);
            sbTitle.Remove(0, sbTitle.Length);
            sbTitle.Append(e.Name);
            if (currentFile.IsReadOnly)
                sbTitle.Append(" 只读");
            if ((currentFile.Attributes & FileAttributes.Hidden) != 0) // 取交集。
                sbTitle.Append(" 隐藏");
            sbTitle.Capacity = sbTitle.Append("        ").Length;
            this.Text = null;
            this.Icon = Icon.ExtractAssociatedIcon(e.FullPath);
            fileWatcher.Filter = e.Name; // 监视重命名的文件。
        }

        private void fileWatcher_Deleted(object sender, FileSystemEventArgs e)
        {
            currentFile.Refresh();
            sbTitle.Remove(0, sbTitle.Length);
            sbTitle.Append(e.Name);
            sbTitle.Capacity = sbTitle.Append("        ").Length;
            this.Text = null;
            attributesMenu.Enabled = false;
        }
        #endregion

        #region RichTextBox.Color
        private void colorButton_Click(object sender, EventArgs e)
        {
            colorDialog.AllowFullOpen = sender.Equals(backColorButton);
            colorDialog.Color = colorDialog.AllowFullOpen ? richText.BackColor : richText.ForeColor;
            if (colorDialog.ShowDialog(this) == DialogResult.OK)
            {
                if (colorDialog.AllowFullOpen)
                    richText.SelectionBackColor = colorDialog.Color;
                else
                    richText.SelectionColor = colorDialog.Color;
            }
        }

        private void foreColorButton_Paint(object sender, PaintEventArgs e)
        {
            using (SolidBrush sb = new SolidBrush(richText.SelectionColor))
            {
                e.Graphics.FillRectangle(sb, 4, 16, foreColorButton.Width - 8, 4);
            }
            e.Dispose();
        }

        private void backColorButton_Paint(object sender, PaintEventArgs e)
        {
            using (SolidBrush sb = new SolidBrush(richText.SelectionBackColor))
            {
                e.Graphics.FillRectangle(sb, 4, 16, backColorButton.Width - 8, 4);
            }
            e.Dispose();
        }

        private void colorComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            richText.BackColor = (Color)colorComboBox.SelectedItem;
        }

        private void colorComboBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0)
                return;
            using (Graphics g = e.Graphics)
            using (SolidBrush sb = new SolidBrush(e.BackColor))
            {
                if ((e.State & DrawItemState.Selected) != 0) // 取交集。
                    sb.Color = Color.BlueViolet;
                Rectangle clip = e.Bounds;
                g.FillRectangle(sb, clip);
                clip.Offset(1, 1);
                clip.Width = 52;
                clip.Height -= 2;
                sb.Color = Color.Black;
                g.FillRectangle(sb, clip);
                clip.Offset(1, 1);
                clip.Width -= 2;
                clip.Height -= 2;
                sb.Color = (Color)colorComboBox.Items[e.Index];
                g.FillRectangle(sb, clip);
                string colorName = sb.Color.Name;
                sb.Color = e.ForeColor;
                g.DrawString(colorName, e.Font, sb, clip.X + 72, clip.Y);
            }
        }
        #endregion

        #region RichTextBox.Edit
        private void undoMenu_Click(object sender, EventArgs e)
        {
            richText.Undo(); // 撤消
        }

        private void redoMenu_Click(object sender, EventArgs e)
        {
            richText.Redo(); // 重复
        }

        private void cutMenu_Click(object sender, EventArgs e)
        {
            richText.Cut(); // 剪切
        }

        private void copyMenu_Click(object sender, EventArgs e)
        {
            richText.Copy(); // 复制
        }

        private void pasteMenu_Click(object sender, EventArgs e)
        {
            if (Clipboard.ContainsFileDropList())
            {
                if (Clipboard.ContainsImage())
                    richText.Paste();
            }
            else if (Clipboard.ContainsText(TextDataFormat.Html))
            {
                string htm = Clipboard.GetText(TextDataFormat.Html);
                richText.SelectedText = Encoding.UTF8.GetString(Encoding.Default.GetBytes(htm));
            }
            else
                richText.Paste(); // 粘贴
        }

        private void deleteMenu_Click(object sender, EventArgs e)
        {
            /* deleteMenu.ShortcutKeyDisplayString = "Delete";
               deleteMenu.ShortcutKeys = Keys.None; */
            SendKeys.Send("{Delete}"); // 删除
        }

        private void selectAllMenu_Click(object sender, EventArgs e)
        {
            richText.SelectAll(); // 全选
        }
        #endregion

        #region RichTextBox.Event
        private void richText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == (Keys.Control | Keys.V))
                e.SuppressKeyPress = Clipboard.ContainsFileDropList() && !Clipboard.ContainsImage();
        }

        private void richText_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            Process.Start(e.LinkText);
        }

        private void richText_SelectionChanged(object sender, EventArgs e)
        {
            Font newFont = richText.SelectionFont;
            if (newFont != null)
            {
                fontNameComboBox.Text = newFont.Name;
                fontSizeComboBox.Text = newFont.Size + "";
                boldButton.Checked = newFont.Bold;
                italicButton.Checked = newFont.Italic;
                underlineButton.Checked = newFont.Underline;
                strikeoutButton.Checked = newFont.Strikeout;
                regularButton.Checked = (newFont.Style == FontStyle.Regular);
            }
            bool flag = (richText.SelectionType != RichTextBoxSelectionTypes.Empty);
            cutMenu.Enabled = cutButton.Enabled = flag;
            copyMenu.Enabled = copyButton.Enabled = flag;
            deleteMenu.Enabled = flag;
            formatStrip.Refresh();
            int row = richText.GetLineFromCharIndex(richText.SelectionStart) + 1;
            int column = richText.SelectionStart + 1 - richText.GetFirstCharIndexOfCurrentLine();
            int lines = richText.GetLineFromCharIndex(richText.TextLength) + 1;
            statusLabelPoint.Text = string.Format("行 {0} 列 {1}        总行数 {2}", row, column, lines);
        }

        private void richText_TextChanged(object sender, EventArgs e)
        {
            undoMenu.Enabled = undoButton.Enabled = richText.CanUndo;
            redoMenu.Enabled = redoButton.Enabled = richText.CanRedo;
            bool flag = (richText.TextLength > 0);
            findMenu.Enabled = findButton.Enabled = flag;
            positionMenu.Enabled = flag;
            selectAllMenu.Enabled = flag;
        }
        #endregion

        #region RichTextBox.Image
        private void imageMenu_Click(object sender, EventArgs e)
        {
            this.OpenFileToFilter(false);
            if (openFile.ShowDialog(this) == DialogResult.OK)
            {
                IDataObject data = Clipboard.GetDataObject();
                foreach (string filePath in openFile.FileNames)
                {
                    using (Bitmap bmp = new Bitmap(filePath))
                    {
                        Clipboard.SetImage(bmp);
                        if (Clipboard.ContainsImage())
                            richText.Paste();
                    }
                }
                Clipboard.SetDataObject(data, true);
            }
        }
        #endregion

        #region RichTextBox.InputDateTime
        private void dateTimeComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            richText.SelectionLength = 0;
            richText.SelectedText = DateTime.Now.ToString((sender as ToolStripComboBox).Text);
        }
        #endregion

        #region RichTextBox.SelectionAlignment
        private void alignmentItem_Click(object sender, EventArgs e)
        {
            switch ((sender as ToolStripItem).Name)
            {
                case "leftMenu":
                case "leftButton":
                    richText.SelectionAlignment = HorizontalAlignment.Left;
                    break;
                case "centerMenu":
                case "centerButton":
                    richText.SelectionAlignment = HorizontalAlignment.Center;
                    break;
                case "rightMenu":
                case "rightButton":
                    richText.SelectionAlignment = HorizontalAlignment.Right;
                    break;
            }
        }
        #endregion

        #region RichTextBox.SelectionBullet
        private void bulletMenu_Click(object sender, EventArgs e)
        {
            richText.BulletIndent = 16;
            richText.SelectionBullet = !richText.SelectionBullet;
        }
        #endregion

        #region RichTextBox.SelectionFont
        private void fontMenu_Click(object sender, EventArgs e)
        {
            fontDialog.Font = richText.SelectionFont;
            fontDialog.Color = richText.SelectionColor;
            if (fontDialog.ShowDialog(this) == DialogResult.OK)
            {
                Font font = fontDialog.Font;
                richText.SelectionFont = font;
                richText.SelectionColor = fontDialog.Color;
                fontNameComboBox.Text = font.Name;
                fontSizeComboBox.Text = font.Size + "";
                boldButton.Checked = font.Bold;
                italicButton.Checked = font.Italic;
                underlineButton.Checked = font.Underline;
                strikeoutButton.Checked = font.Strikeout;
                regularButton.Checked = (font.Style == FontStyle.Regular);
            }
        }

        private void fontNameComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                using (Font oldFont = richText.SelectionFont)
                {
                    if (oldFont != null)
                        richText.SelectionFont = new Font(fontNameComboBox.Text, oldFont.Size, oldFont.Style);
                }
            }
            catch
            {
                return;
            }
        }

        private void fontSizeComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (Font oldFont = richText.SelectionFont)
            {
                if (oldFont != null)
                    richText.SelectionFont = new Font(oldFont.Name, float.Parse(fontSizeComboBox.Text), oldFont.Style);
            }
        }

        private void fontStyleButton_Click(object sender, EventArgs e)
        {
            ToolStripButton styleButton = sender as ToolStripButton;
            styleButton.Checked = !styleButton.Checked;
            regularButton.Checked = false;
            FontStyle newStyle = FontStyle.Bold;
            switch (styleButton.Name)
            {
                case "boldButton":
                    break;
                case "italicButton":
                    newStyle = FontStyle.Italic;
                    break;
                case "underlineButton":
                    newStyle = FontStyle.Underline;
                    break;
                case "strikeoutButton":
                    newStyle = FontStyle.Strikeout;
                    break;
            }
            using (Font oldFont = richText.SelectionFont)
            {
                if (oldFont != null)
                    richText.SelectionFont = new Font(oldFont, oldFont.Style ^ newStyle);
            }
        }

        private void fontRegularButton_Click(object sender, EventArgs e)
        {
            boldButton.Checked = false;
            italicButton.Checked = false;
            underlineButton.Checked = false;
            strikeoutButton.Checked = false;
            regularButton.Checked = true;
            using (Font oldFont = richText.SelectionFont)
            {
                if (oldFont != null)
                    richText.SelectionFont = new Font(oldFont, FontStyle.Regular);
            }
        }
        #endregion

        #region RichTextBox.SortOrder
        private void sortOrderButton_Click(object sender, EventArgs e)
        {
            if (sortOrderButton.Checked = !sortOrderButton.Checked)
            {
                var query = from line in richText.Lines
                            orderby line ascending
                            select line;
                richText.Lines = query.ToArray();
                sortOrderButton.ToolTipText = "降序排序";
            }
            else
            {
                var query = from line in richText.Lines
                            orderby line descending
                            select line;
                richText.Lines = query.ToArray();
                sortOrderButton.ToolTipText = "升序排序";
            }
        }
        #endregion

        #region OwnedForms
        private void ShowModal(Form frame)
        {
            frame.Icon = this.Icon;
            frame.MaximizeBox = false;     // 隐藏“最大化”按钮。
            frame.MinimizeBox = false;    // 隐藏“最小化”按钮。
            frame.ShowInTaskbar = false; // 在 Windows 任务栏中隐藏窗体。
            frame.StartPosition = FormStartPosition.CenterScreen; // 在桌面居中显示。
            frame.SizeGripStyle = SizeGripStyle.Hide; // 隐藏调整大小手柄。
            frame.AutoSizeMode = AutoSizeMode.GrowAndShrink; // 禁用窗体调整大小。
            frame.FormBorderStyle = FormBorderStyle.Sizable; // 可调整大小的边框。
            frame.FormClosing += new FormClosingEventHandler(frame_FormClosing);
            frame.Show(this);
        }

        private void frame_FormClosing(object sender, FormClosingEventArgs e)
        {
            AnimateWindow((sender as Form).Handle, 1000, 0x90000);
        }

        private void aboutMenu_Click(object sender, EventArgs e)
        {
            this.ShowModal(new FormAboutBox());
        }

        private void findMenu_Click(object sender, EventArgs e)
        {
            this.ShowModal(new FormFindText(richText));
        }

        private void attributesMenu_Click(object sender, EventArgs e)
        {
            currentFile.Refresh();
            if (currentFile.Exists)
                this.ShowModal(new FormAttributes(currentFile));
            else
                MessageBox.Show(this, string.Format("当前文件 {0} 不存在。", currentFile.FullName), "写字板", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void charOffsetMenu_Click(object sender, EventArgs e)
        {
            FormOffsetPosition frame = new FormOffsetPosition(richText);
            frame.Text = "上标/下标";
            frame.Tag = false;
            this.ShowModal(frame);
        }

        private void positionMenu_Click(object sender, EventArgs e)
        {
            FormOffsetPosition frame = new FormOffsetPosition(richText);
            frame.Text = "定位";
            frame.Tag = true;
            this.ShowModal(frame);
        }

        private void screenMenu_Click(object sender, EventArgs e)
        {
            this.Hide();
            using (FormScreen frame = new FormScreen())
            {
                frame.ShowDialog(this);
                if (Clipboard.ContainsImage())
                    richText.Paste();
            }
            this.Show();
        }

        private void showHelpMenu_Click(object sender, EventArgs e)
        {
            Help.ShowHelp(this, "wordpad.chm");
        }
        #endregion

        #region TimerInfo
        private void timerInfo_Tick(object sender, EventArgs e)
        {
            if (this.Text.Length < sbTitle.Length)
                this.Text = sbTitle.ToString(0, this.Text.Length + 1);
            else
            {
                sbTitle.Append(sbTitle[0]);
                this.Text = sbTitle.Remove(0, 1).ToString();
            }
            DateTime solar = DateTime.Now;
            int year = lunarCalendar.GetYear(solar);
            int month = lunarCalendar.GetMonth(solar);
            int leapMonth = lunarCalendar.GetLeapMonth(year);
            if (0 < leapMonth && leapMonth <= month)
                --month;
            statusLabelTime.Text = string.Format("{0:F} [{1}年 {2} {3:00}]", solar, animals[(year - 4) % 12], DateTimeFormatInfo.CurrentInfo.MonthNames[month - 1], lunarCalendar.GetDayOfMonth(solar));
            if (addZoomFactorButton.Pressed ^ subZoomFactorButton.Pressed)
            {
                richText.ZoomFactor += addZoomFactorButton.Pressed ? 0.5F : -0.5F;
                addZoomFactorButton.Enabled = (richText.ZoomFactor < 10F);
                subZoomFactorButton.Enabled = (richText.ZoomFactor > 1F);
            }
        }
        #endregion

        #region Appendix
        private void mspaintMenu_Click(object sender, EventArgs e)
        {
            using (Process psi = new Process())
            {
                psi.StartInfo.FileName = "mspaint.exe"; // 画图。
                psi.StartInfo.WorkingDirectory = Environment.SystemDirectory;
                psi.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
                psi.Start();
            }
        }

        private void charmapMenu_Click(object sender, EventArgs e)
        {
            using (Process psi = new Process())
            {
                psi.StartInfo.FileName = "charmap.exe"; // 字符映射表。
                psi.StartInfo.WorkingDirectory = Environment.SystemDirectory;
                psi.Start();
            }
        }
        #endregion

        #region Application.CurrentCulture
        private void cultureComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Application.CurrentCulture = cultureComboBox.SelectedItem as CultureInfo;
            DateTimeFormatInfo info = DateTimeFormatInfo.CurrentInfo;
            timeComboBox.Items.Clear();
            timeComboBox.Items.AddRange(info.GetAllDateTimePatterns('T'));
            timeComboBox.Items.AddRange(info.GetAllDateTimePatterns('d'));
            timeComboBox.Items.AddRange(info.GetAllDateTimePatterns('D'));
            dateComboBox.Items.Clear();
            dateComboBox.Items.AddRange(timeComboBox.Items.Cast<object>().ToArray());
        }
        #endregion

        #region Application.CurrentInputLanguage
        private void languageComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Application.CurrentInputLanguage = languageComboBox.SelectedItem as InputLanguage;
        }
        #endregion

        #region Application.CurrentCulture.TextInfo
        private void textInfoButton_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            int start = richText.SelectionStart;
            int length = richText.SelectionLength;
            TextInfo info = Application.CurrentCulture.TextInfo;
            switch (textInfoButton.DropDownItems.IndexOf(e.ClickedItem))
            {
                case 0:
                    richText.SelectedText = info.ToLower(richText.SelectedText); // 将指定的字符串转换为小写。
                    break;
                case 1:
                    richText.SelectedText = info.ToUpper(richText.SelectedText); // 将指定的字符串转换为大写。
                    break;
                case 2:
                    richText.SelectedText = info.ToTitleCase(richText.SelectedText); // 将指定的字符串转换为词首字母大写。
                    break;
                case 3:
                    sbText.Remove(0, sbText.Length);
                    foreach (char c in richText.SelectedText)
                    {
                        char sc = (char.IsLower(c) || char.IsUpper(c)) ? (char)(c ^ 32) : c;
                        sbText.Append(sc);
                    }
                    richText.SelectedText = sbText.ToString(); // 切换大小写。
                    sbText.Capacity = sbText.Remove(0, sbText.Length).Length;
                    break;
            }
            richText.Select(start, length);
        }
        #endregion
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值