利用 MenuStrip 做多國語言的切換

相關的參考,在程式中有備註

初始畫面會先跑預設語言

選擇語言檔設定的語系

語言檔的內容設定


Code Snip
Public Class frmMain

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        MenuStrip1.Font = New Font("arial", 10)
        tsLanguage.Font = New Font("arial", 10)

        Dim lines As String() = StrArr()
        For i As Integer = 0 To lines.Length - 1
            If Mid(lines(i), 3, 1) = "-" Then tsLanguage.Items.Add(lines(i))
        Next
        tsLanguage.SelectedIndex = 0
    End Sub

    '轉換語系
    Private Sub tsLanguage_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tsLanguage.SelectedIndexChanged
        Me.Cursor = Cursors.WaitCursor
        '獲得語系檔
        Dim lines As String() = StrArr()
        For i As Integer = 0 To lines.Length - 1
            '比對語系所在列數
            If tsLanguage.SelectedItem = lines(i) Then
                '底下程式太長太亂,另開副程序開始置換
                CollectionCtrl(lines, i + 1)
            End If
        Next
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub CollectionCtrl(ByVal lines() As String, ByVal CurRow As Integer)
        '置換迴圈
        For i As Integer = CurRow To lines.Length - 1
            '直到檔尾或下一個語系:例 en-us 的 "-" 請不要更改
            If Mid(lines(i), 3, 1) = "-" Then Exit Sub
            '搜尋表單上的控制項
            For Each ctrl As Control In Controls
                '語系檔該行空白不比對
                If lines(i) <> Nothing Then
                    Select Case ctrl.Name
                        '由於物件特性,底下物件必須遞迴才能找到
                        Case "MenuStrip1"
                            Dim ts As ToolStrip = CType(ctrl, ToolStrip)
                            For j As Integer = 0 To ts.Items.Count - 1
                                tsRecursive(ts.Items(j), lines, i)
                            Next
                        Case Else
                            If ctrl.Tag = Trim(Split(lines(i), "=")(0)) Then _
                               ctrl.Text = Trim(Split(lines(i), "=")(1))
                    End Select
                End If
            Next
        Next
    End Sub

    Private Sub tsRecursive(ByVal tsmi As ToolStripMenuItem, ByVal lines() As String, ByVal CurRow As Integer)
        On Error Resume Next
        If tsmi.Tag = Trim(Split(lines(CurRow), "=")(0)) Then _
           tsmi.Text = Trim(Split(lines(CurRow), "=")(1))
        '遞迴
        For i As Integer = 0 To tsmi.DropDownItems.Count - 1
            tsRecursive(tsmi.DropDownItems(i), lines, CurRow + 1)
        Next
    End Sub

    Private Function StrArr() As String()
        '語系檔在相對目錄 \language\bin\Debug\
        Dim txtReader As IO.StreamReader = IO.File.OpenText(Application.StartupPath & "\Language.ini")
        Dim fileContents As String = txtReader.ReadToEnd()
        txtReader.Close()
        Return Split(fileContents, Environment.NewLine)
    End Function
End Class

沒有留言:

張貼留言