漢字字源教學測試頁排版置入內容 vbscript

View Snippet
                    Sub 漢字字源教學測試頁排版置入內容()
'要先輸入好字頭,並且將插入點置於字頭內容段落內
Dim d字源圖片 As Document, theD As Document, d1 As Document
Dim p As Paragraph, rng As Range, inlsp As InlineShape
Dim x As String
Set d字源圖片 = Documents("!!!@@@###字源圖片.docx")
Set theD = ActiveDocument
Set d1 = Documents(1) '原字源檔
With theD.ActiveWindow.Selection.Paragraphs(1).Range
    x = .Characters(1)
    With .Characters(3)
        .Text = x
        .Select
        Application.WordBasic.toolsTcScTranslate Direction:=0, Varients:=0, Translatecommon:=0
    End With
    .Characters(8).Text = VBA.IIf(注音拼音.漢字轉拼音(x) = Null, "", 注音拼音.漢字轉拼音(x))
    .Characters(6).Text = VBA.IIf(注音拼音.漢字轉注音(x) = Null, "", 注音拼音.漢字轉注音(x))
End With
theD.ActiveWindow.Selection.MoveDown
For Each p In d1.Paragraphs
    If p.Range.Characters.Count > 3 Then
        If p.Range.Characters(3).Font.Size = 14 Then
            Set rng = p.Range
            rng.SetRange p.Range.Characters(1).Start, p.Range.Characters(p.Range.Characters.Count - 1).End
            rng.Copy
            '先選好要覆蓋過去的段落
            With theD.ActiveWindow.Selection
                .Paragraphs(1).Range.Select
                .MoveLeft wdCharacter, 1, wdExtend
                .Paste
                .MoveDown
            End With
            If p.Next.Range.Text Like "  以下是「*" Then Exit For
        End If
    End If
Next
'調整靜態筆順圖大小及「」內的字
Dim np As Paragraph
Set np = theD.ActiveWindow.Selection.Paragraphs(1)
Do
    If InStr(np.Range.Text, "」字書寫的筆順是") > 0 Then
        np.Range.Characters(4) = x 'theD.Tables(1).Rows(2).Cells(6).Range.Characters(1)
        If np.Range.InlineShapes.Count = 0 Then '插入靜態筆順圖
            If Dir("E:\@@@華語文工具及資料@@@\!!@詞典附檔@!\筆順圖形\*" & x & "*.jpg") <> "" Then
                np.Range.Characters(13).InlineShapes.AddPicture _
                    "E:\@@@華語文工具及資料@@@\!!@詞典附檔@!\筆順圖形\" & _
                    Dir("E:\@@@華語文工具及資料@@@\!!@詞典附檔@!\筆順圖形\*" & x & "*.jpg")
            End If
        End If
        For Each inlsp In np.Range.InlineShapes
            inlsp.LockAspectRatio = msoTrue
            inlsp.Height = 20.65
        Next
        np.Next.Range.Select
        Exit Do
    End If
    Set np = np.Next
Loop
''處理表格內的字圖
Dim c As Cell, ri As Long, ci As Byte, tb As Table
Set tb = theD.ActiveWindow.Selection.Tables(1)
For Each c In d字源圖片.Tables(1).Columns(1).Cells
    If InStr(c.Range, x) > 0 Then
        ri = c.RowIndex
'        c.Next.Select
'        d字源圖片.
        Exit For
    End If
Next
If ri = 0 Then 'd字源圖片沒有的話
        For Each c In d1.Tables(1).Rows(2).Cells
            ci = ci + 1
            If c.Range.InlineShapes.Count > 0 Then
                c.Range.InlineShapes(1).Range.Select
                d1.ActiveWindow.Selection.Copy
                With tb.Cell(2, ci).Range
                    If .InlineShapes.Count > 0 Then
                        .InlineShapes(1).Range.Select
                    Else
                        .Characters(1).Select
                    End If
                    .Paste
                    With .InlineShapes(1)
                        .LockAspectRatio = msoTrue
                        Select Case ci
                            Case 1  '甲骨文
                                .Height = 27.2
                            Case 2
                                .Height = 30
                            Case 3
                                
                            Case 4
                            Case 5 '行書
                                .Height = 37.7
                        End Select
                    End With
                End With
            Else '結果沒圖
                'c.Range.Characters(1).Copy
                tb.Cell(2, ci).Range.Text = Replace(Replace(c.Range.Text, Chr(13), ""), Chr(7), "")
            End If
    Next

Else
    For Each c In d字源圖片.Tables(1).Rows(ri).Cells
        If c.ColumnIndex > 7 Then Exit For '到楷書為止
        If c.ColumnIndex > 1 Then
            ci = ci + 1
            If c.Range.InlineShapes.Count > 0 Then
                c.Range.InlineShapes(1).Range.Select
                d字源圖片.ActiveWindow.Selection.Copy
                With tb.Cell(2, ci).Range
                    If .InlineShapes.Count > 0 Then
                        .InlineShapes(1).Range.Select
                    Else
                        .Characters(1).Select
                    End If
                    .Paste
                    With .InlineShapes(1)
                        .LockAspectRatio = msoTrue
                        Select Case ci
                            Case 1  '甲骨文
                                .Height = 27.2
                            Case 2
                                .Height = 30
                            Case 3
                                
                            Case 4
                            Case 5 '行書
                                .Height = 37.7
                        End Select
                    End With
                End With
            Else '結果沒圖
                'c.Range.Characters(1).Copy
                tb.Cell(2, ci).Range.Text = Replace(Replace(c.Range.Text, Chr(13), ""), Chr(7), "")
            End If
        End If
    Next
    tb.Cell(2, ci + 1).Range.Text = Replace(Replace(tb.Cell(2, ci).Range.Text, Chr(13), ""), Chr(7), "")
    tb.Cell(2, ci + 1).Range.Characters(1).Select
    Application.WordBasic.toolsTcScTranslate Direction:=0, Varients:=0, Translatecommon:=0
End If
' 插入原有字源解說大圖
With d1.InlineShapes(d1.InlineShapes.Count)
    If .Height > 70 Then
        .Range.Select
        d1.ActiveWindow.Selection.Copy
        With theD.ActiveWindow.Selection
            '.MoveDown , 3
            .MoveUntil Chr(12)
            .Paste
'            .Paragraphs(1).LineSpacingRule = wdLineSpaceSingle
        End With
    End If
End With
With theD.ActiveWindow
    .Activate
    If .Selection.Sections(1).Range.Paragraphs(2).Range.Font.Size <> 14 Then .Selection.Sections(1).Range.Paragraphs(2).Range.Font.Size = 14
End With
If tb.Cell(2, ci + 1).Range.Text <> tb.Cell(2, ci).Range.Text Then MsgBox "請插入簡化字靜態筆順!", vbExclamation
End Sub


                  

Word圖檔不壓縮 csharp

View Snippet
                    using Microsoft.Office.Interop.Word;//https://social.msdn.microsoft.com/Forums/office/en-US/c6a73b86-d388-4733-8e5b-d00742b40dd7/turn-off-picture-compression-in-interop?forum=worddev

// ...

string imagePath = @"c:\temp\win10.jpg";

Application wordApp = new Application();
Document wordDoc = wordApp.Documents.Add();

// Create an InlineShape in the InlineShapes collection where the picture should be added later
// It is used to get automatically scaled sizes.
InlineShape autoScaledInlineShape = wordDoc.InlineShapes.AddPicture(imagePath);
float scaledWidth = autoScaledInlineShape.Width;
float scaledHeight = autoScaledInlineShape.Height;

// Create a new Shape and fill it with the picture
Shape newShape = wordDoc.Shapes.AddShape(1, 0, 0, scaledWidth, scaledHeight);
newShape.Fill.UserPicture(imagePath);

// Convert the Shape to an InlineShape and optional disable Border
InlineShape finalInlineShape = newShape.ConvertToInlineShape();
finalInlineShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;

// Cut the range of the InlineShape to clipboard
autoScaledInlineShape.Delete();
finalInlineShape.Range.Cut();

// optional create new Range
Range docRange = wordDoc.Range();

// And paste it to the target Range
docRange.Paste();

wordDoc.SaveAs2(@"c:\temp\test.docx");
wordDoc.Close();
wordApp.Quit();
                  

BiHua筆畫插字 vbscript

View Snippet
                    Sub BiHua() '指定筆畫後列出該筆畫可供取名之字 Alt+w
Dim rst As New ADODB.Recordset
Dim x As String ', bs As Byte
system.cntOpen
If Selection.Type = wdSelectionIP Then Exit Sub
x = Selection
Selection.Font.Name = "標楷體"
Selection.Font.Size = 16
Selection.ParagraphFormat.LineSpacingRule = wdLineSpaceExactly
Selection.ParagraphFormat.LineSpacing = 20

If Not IsNumeric(x) Then Exit Sub
If CByte(x) > 25 Or CByte(x) < 4 Then Exit Sub
system.cntOpen
rst.Open "select 字,命名筆畫驗算過,部首ID from 字 where 命名筆畫 = " & CInt(x) & " and 取名字=true order by 部首ID,字", cnt, adOpenKeyset, adLockReadOnly
With rst
    Selection.MoveRight wdCharacter, 4, wdMove
    Do Until .EOF
'        If bs <> VBA.CByte(.Fields("部首ID").Value) Then Selection.TypeText Chr(11)
'        bs = VBA.CByte(.Fields("部首ID").Value)
        If .Fields("命名筆畫驗算過").Value = -1 Then
            Selection.Font.ColorIndex = wdAuto
        Else
            Selection.Font.ColorIndex = wdRed
        End If
        Selection.TypeText .Fields("字").Value
        .MoveNext
    Loop
End With
rst.Close
cnt.Close
End Sub


                  

字源小篆批量插入圖片 csharp

View Snippet
                    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using word=Microsoft.Office.Interop.Word;
using System.IO;
using System.Globalization;

namespace 字源小篆批量插入圖片
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (checkout() == true) 
            {
                InsertPictoDocx();
                MessageBox.Show("完成","",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }

        bool checkout()
        {
            if (textBox1.Text != "" && textBox2.Text != "")
            {
                return true;
            }
            else
            {
                return false;
            }
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //textBox1.Text = @"C:\Users\123\Music\@@@小篆\小篆(全)";
            //textBox2.Text=@"C:\Users\123\Desktop\@20180427字源\A漢字書240字(缺033)";
        }

        void InsertPictoDocx()
        {
            word.Application wd = new word.Application();
            var picFls = Directory.GetFiles(textBox1.Text);
            var wordFls = Directory.GetFiles(textBox2.Text);
            string w = ""; bool ok=false;
            //word.Dialog dlg = word._Application.Dialogs[Word.WdWordDialog.wdDialogFileOpen];
                //word._ApplicationClass.Dialogs[Word.WdWordDialog.wdDialogFileOpen];
            //word.Dialogs wDlgs;
            //var wDlgss = wDlgs.GetEnumerator();
            //word.Dialog dlg = wDlgss[word.WdWordDialog.wdDialogFileOpen];
            //dlg.Show(); dlg.Show();
            
            foreach (var pf in picFls)
            {
                StringInfo uw = new StringInfo(pf);
                w=uw.SubstringByTextElements(uw.LengthInTextElements - 5, 1);//取得字
                //找word檔docx
                foreach (var f in wordFls)
                {
                    if (f.IndexOf(w) > -1 && f.Substring( f.LastIndexOf(".")) ==".docx" && f.Substring(0,2)!="~$")//找到的話
                    {
                        word.Document d = wd.Documents.Open(f);                        
                        
                        foreach (word.Table t in d.Tables)
                        {
                            if (t.Cell(2, 6).Range.Characters[1].Text == w)
                            {
                                d.ActiveWindow.Visible = true;
                                if (t.Cell(2, 3).Range.InlineShapes.Count>0)
                                {
                                    foreach (word.InlineShape item in t.Cell(2, 3).Range.InlineShapes)
                                    {
                                        item.Delete();
                                    }
                                }
                                t.Cell(2, 3).Range.Text = "";
                                t.Cell(2, 3).Range.InlineShapes.AddPicture(pf);
                                t.Cell(2, 3).Range.InlineShapes[1].Height = float.Parse("35.4");
                                t.Cell(2, 3).Range.InlineShapes[1].Width = float.Parse("26");
                            }
                        }
                        //https://www.google.com.tw/search?ei=9-frWqWtNMiI8wXcoZBY&q=word+%22C%23%22+%22option%22+pic+do+not+compress&oq=word+%22C%23%22+%22option%22+pic+do+not+compress&gs_l=psy-ab.3...4979.6442.0.6712.2.2.0.0.0.0.81.137.2.2.0....0...1.1.64.psy-ab..0.0.0....0.8TaNEzUEcnI
                        //d.Application.Options.comp 
                        //顯示選項設定詩話框//https://stackoverflow.com/questions/42392585/office-interop-access-ms-word-advanced-options
                        //d.Application.Dialogs[word.WdWordDialog.wdDialogToolsAdvancedSettings].Show();選項進階對話框
                        //d.Application.Dialogs[word.WdWordDialog.wdDialogFileOpen].Show();//開啟舊檔對話框
                        d.Application.ScreenRefresh();
                        d.Application.Dialogs[word.WdWordDialog.wdDialogToolsOptions].Show();
                        /*https://msdn.microsoft.com/en-us/library/ahzbkf8e.aspx
                        */
                        //System.Diagnostics.Debugger.Break();//https://social.msdn.microsoft.com/Forums/vstudio/en-US/db9dfe97-c98d-4f4b-bb8f-ba2edffee988/can-i-do-a-visual-basic-vb-stop-in-c?forum=csharpgeneral
                        d.SaveAs2(Type.Missing, Type.Missing, Type.Missing, Type.Missing, false);
                        d.Close();
                        File.Move(f, f.Replace(textBox2.Text, textBox3.Text));//https://tinyurl.com/y8h6wxqa
                        ok = true;

                        break;
                    }//以上為word檔案處理
                }
                if (ok==false)
                {
                    //MessageBox.Show("找不到「" + w + "」的字源檔案!");
                    ////System.Diagnostics.Debugger.Break();
                }
            }
            ok = false;
        }
    }
}

                  

姓名學字彙輸入 csharp

View Snippet
                    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();
        }
    }
}