姓名學字彙輸入 csharp

                  using System;
//using System.Collections.Generic;
//using System.ComponentModel;
//using System.Data;
using System.Drawing;
using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
using System.Windows.Forms;
using ado=ADODB;
using System.Globalization;
using System.IO;
using word = Microsoft.Office.Interop.Word;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace 姓名學字彙輸入
{
    public partial class Form1 : Form
    {
        ado.Connection Cnt = new ado.Connection();
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {
            textBox1.Focus();
            textBox1.SelectAll();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (OpenDataBase())
            {
                comboBox1Ready();

            }
        }

        private void comboBox1Ready()
        {
            ado.Recordset rst = new ado.Recordset();
            rst.Open("部首",Cnt,ado.CursorTypeEnum.adOpenStatic,ado.LockTypeEnum.adLockReadOnly);
            comboBox1.BeginUpdate();
            do
            {
                comboBox1.Items.Add(rst.Fields["部首"].Value);
                rst.MoveNext();
            } while (!rst.EOF);
            comboBox1.EndUpdate();rst.Close();
            //throw new NotImplementedException();
        }

        private bool OpenDataBase()
        {
            //string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Microsoft\Templates";
            if  ( File.Exists( path + @"\詞典.mdb"))
            {
                string strCnt = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + @"\詞典.mdb";
                Cnt.Open(strCnt);return true;
            }
            else
            {
                MessageBox.Show("「詞典」檔案不在「" + path + "」路徑下,請予複製/安裝 \n感恩感恩 南無阿彌陀佛");
                if (System.Windows.Forms.Application.MessageLoop)
                {//https://stackoverflow.com/questions/12977924/how-to-properly-exit-a-c-sharp-application
                    // WinForms app
                    System.Windows.Forms.Application.Exit();
                }
                else
                {
                    // Console app
                    System.Environment.Exit(1);
                }
                return false;
            }
            
            
            //throw new NotImplementedException();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("請輸入筆畫");
                return;
            }
            if (!Is_Number(textBox1.Text) || textBox2.Text.Trim() == "" || textBox1.Text == "")
            {
                return;
            }
            if (IsNatural_Number(textBox2.Text))
            {
                MessageBox.Show("請輸入中文字!");
                return;
            }


            if (Char.IsSurrogatePair(textBox2.Text,0))
            {
                if (wordLength(textBox2.Text) != 1)
                {
                    MessageBox.Show("只能是一個字!");
                    return;
                }
            }
            else
            {
                if (!Char.IsHighSurrogate(Convert.ToChar(textBox2.Text)))//https://msdn.microsoft.com/zh-tw/library/xcwwfbb8(v=vs.110).aspx
                                                                         //if (Char.IsSurrogatePair(Convert.ToChar(textBox2.Text)))
                {
                    if (wordLength(textBox2.Text) != 1)
                    {
                        MessageBox.Show("只能是一個字!");
                        return;
                    }
                }
                else
                {
                    return;
                }

            }
            editRecord();
            textBox2.SelectAll();
        }
        
        public bool IsNatural_Number(string str)//判斷傳入的字符是否是英文字母或數字 http://rogerangelhome.blogspot.tw/2010/05/c-c.html

        {

            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]+$");
            return reg1.IsMatch(str);
        }

        //判斷傳入的字符是否是數字 http://rogerangelhome.blogspot.tw/2010/05/c-c.html
        public bool Is_Number(string str)

        {

            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9]+$");

            return reg1.IsMatch(str);

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (!Is_Number(textBox1.Text))
            {
                MessageBox.Show("請輸入數字");
                textBox1.Text = "";
                return;
            }
            int bh = Int32.Parse( textBox1.Text);
            if  (bh<1||bh>45)//http://dict.variants.moe.edu.tw/variants/rbt/query_by_stroke_tiles.rbt?command=clear
            {                
                MessageBox.Show("請檢查筆畫!");
                return;
            }
            if (bh>30 )
            {
                MessageBox.Show("請檢查筆畫!");
            }
               
        }

        int wordLength(string w)
        {
            StringInfo si = new StringInfo(w);
            return si.LengthInTextElements;
        }

        void editRecord()
        {
            ado.Recordset rst = new ado.Recordset();
            //if( Cnt.State==0)
            //{
            //    return;
            //}
            rst.Open(@"select 字,命名筆畫,命名筆畫驗算過,取名字 from 字 where strcomp(字,""" + textBox2.Text + @""")=0", Cnt, ado.CursorTypeEnum.adOpenKeyset, ado.LockTypeEnum.adLockOptimistic);
            if (rst.RecordCount > 0)
            {
                if (rst.Fields["命名筆畫驗算過"].Value)
                {
                    if (MessageBox.Show("大菩薩,「" + textBox2.Text + "」字已驗算過!確定更改?筆畫為" + Convert.ToString(rst.Fields["命名筆畫"].Value) + "\n南無阿彌陀佛", "watch out!!", MessageBoxButtons.OKCancel,MessageBoxIcon.Exclamation,MessageBoxDefaultButton.Button2)==DialogResult.Cancel)
                    {
                        return;
                    }
                }
                if (Convert.ToInt32( rst.Fields["命名筆畫"].Value)!=Int32.Parse( textBox1.Text))
                {
                    if (MessageBox.Show("大菩薩,「"+textBox2.Text +  "」原擬定的筆畫為" + Convert.ToString(rst.Fields["命名筆畫"].Value)+ "!確定更改? \n南無阿彌陀佛", "watch out!! ", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.Cancel)
                    {
                        return;
                    }

                }
                rst.Fields["命名筆畫"].Value = textBox1.Text;
                rst.Fields["命名筆畫驗算過"].Value = -1;
                rst.Fields["取名字"].Value = -1;
                rst.Update();
            }
            else
            {
                rst.AddNew();
                rst.Fields["字"].Value = textBox2.Text;
                rst.Fields["命名筆畫"].Value = textBox1.Text;
                rst.Fields["命名筆畫驗算過"].Value = -1;
                rst.Fields["取名字"].Value = -1;
                MessageBox.Show("記得輸入部首!南無阿彌陀佛","缺部首!",MessageBoxButtons.OK,MessageBoxIcon.Information);
                comboBox1.Focus();
                comboBox1.BackColor = Color.Yellow;
                rst.Update();
            }
            rst.Close();
            return;
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode== Keys.Escape)
            {
                textBox2.Text = "";
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (Cnt.State==1)//ado.ObjectStateEnum.adStateOpen
            {
                Cnt.Close();
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {
            textBox2.Focus();
            textBox2.SelectAll();
        }

        private void label3_Click(object sender, EventArgs e)
        {
            comboBox1.Focus();
            comboBox1.SelectAll();
        }

        void BuShouInput(string bs)//輸入部首
        {
            if (bs != "" && wordLength(bs) == 1)
            {
                ado.Recordset rst = new ado.Recordset();
                rst.Open(@"select 部首ID from 部首 where strcomp(部首,""" + bs + @""")=0", Cnt, ado.CursorTypeEnum.adOpenKeyset, ado.LockTypeEnum.adLockOptimistic);
                if (rst.RecordCount != 1)
                {
                    MessageBox.Show("大菩薩,輸入的部首有誤!請重新輸入!!\r感恩感恩 南無阿彌陀佛", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    comboBox1.Text = "";rst.Close(); return;
                }
                int bsID = rst.Fields[0].Value;
                rst.Close();
                rst.Open(@"select 部首ID from 字 where strcomp(字,"""+ textBox2.Text.Trim()+@""")=0",Cnt,ado.CursorTypeEnum.adOpenKeyset,ado.LockTypeEnum.adLockOptimistic);
                if (rst.RecordCount!=1)
                {
                    MessageBox.Show("大菩薩,輸入的部首或字彙有誤!請重新輸入!!\r感恩感恩 南無阿彌陀佛", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    comboBox1.Text = ""; textBox2.Text="" ; rst.Close(); return;
                }
                rst.Fields[0].Value = bsID;rst.Update();
                comboBox1.Text = "";comboBox1.BackColor = Color.White;
                textBox2.Focus();
                rst.Close();return;                
            }

        }


        private void textBox2_Enter(object sender, EventArgs e)
        {
            if (comboBox1.BackColor == Color.Yellow)
            {
                MessageBox.Show("大菩薩,請先完成部首輸入哦! \n感恩感恩 南無阿彌陀佛","",MessageBoxButtons.OK,MessageBoxIcon.Stop);
                comboBox1.Focus();
                return;
            }
        }

        private void comboBox1_TextUpdate(object sender, EventArgs e)
        {
            if (comboBox1.FindStringExact(comboBox1.Text)==-1)
            {
                MessageBox.Show("大菩薩,部首輸入錯誤,請重新輸入 或在下拉清單中點選 感恩感恩 \n南無阿彌陀佛","",MessageBoxButtons.OK,MessageBoxIcon.Error);
                comboBox1.Text = "";                
            }
            else
            {
                BuShouInput(comboBox1.Text.Trim());
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            BuShouInput(comboBox1.Text.Trim());
        }

        private void comboBox1_Enter(object sender, EventArgs e)
        {
            if (textBox2.Text == "" || wordLength(textBox2.Text.Trim()) != 1)
            {
                MessageBox.Show("大菩薩,字彙輸入有誤或未輸入!請重新輸入!!\r感恩感恩 南無阿彌陀佛", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                textBox2.Focus();
                comboBox1.BackColor =Color.White;
                return;
            }

        }

        private bool ProcessExists(int id)//https://stackoverflow.com/questions/1545270/how-to-determine-if-a-process-id-exists
        {
            return Process.GetProcesses().Any(x => x.Id == id);
        }

        int Pid=-1;
        private void button1_Click(object sender, EventArgs e)
        {
            if ( Is_Number( textBox1.Text)==false)
            {
                MessageBox.Show("大菩薩,筆畫要是數字喔!\n感恩感恩 南無阿彌陀佛");
                return;
            }

            ado.Recordset rst = new ado.Recordset();
            rst.Open("select 字,命名筆畫驗算過,部首ID from 字 where 命名筆畫 = " + int.Parse(textBox1.Text) + " and 取名字=true order by 部首ID,字", Cnt, ado.CursorTypeEnum.adOpenKeyset, ado.LockTypeEnum.adLockReadOnly);
            if (rst.RecordCount == 0)
            {
                MessageBox.Show("大菩薩,沒有"+ textBox1.Text+"畫的字喔!\n感恩感恩 南無阿彌陀佛");
                rst.Close();
                return;
            }

            word.Application wd;
            if (ProcessExists(Pid))
            {
                //wd = (word.Application)Marshal.GetActiveObject(Pid.ToString());此無效!
                //wd = (word.Application)Marshal.GetActiveObject("Word.Application");
                try
                {
                    wd = Marshal.GetActiveObject("Word.Application") as word.Application;
                }
                catch (Exception)
                {
                    wd = NewWordApp();
                    //throw;
                }                
            }
            else
            {
                wd=NewWordApp();
                    }
            word.Document d = wd.Documents.Add();
            d.ActiveWindow.Visible = true;wd.Activate();
            d.ActiveWindow.Selection.Font.Name = "標楷體";
            d.ActiveWindow.Selection.Font.Size = 16;
            d.ActiveWindow.Selection.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceExactly;
            d.ActiveWindow.Selection.ParagraphFormat.LineSpacing = 20;
            d.ActiveWindow.Selection.TypeText(textBox1.Text);


            do
            {
                if (rst.Fields["命名筆畫驗算過"].Value ==true)
                {
                    d.ActiveWindow.Selection.Font.ColorIndex = word.WdColorIndex.wdAuto;
                }
                else
                {
                    d.ActiveWindow.Selection.Font.ColorIndex = word.WdColorIndex.wdRed;

                }
                d.ActiveWindow.Selection.TypeText(rst.Fields["字"].Value);
                if(d.ActiveWindow.Selection.Font.Name != "標楷體")
                {
                    d.ActiveWindow.Selection.Font.Name = "標楷體";
                }
                rst.MoveNext();
            } while (!rst.EOF);
            rst.Close();
        }

        private word.Application NewWordApp()
        {
            word.Application wd = new word.Application();
            Process[] WordProcesses = Process.GetProcessesByName("WinWord");//https://social.msdn.microsoft.com/Forums/en-US/f7d1749c-0cc2-4821-953c-89d518d804d1/getting-pid-of-created-ms-word-instance?forum=vblanguage
            Pid = WordProcesses[WordProcesses.GetUpperBound(0)].Id;
            return wd;
            //throw new NotImplementedException();
        }
    }
}