[Implement] TextBox 字串輸入時自動將全形字轉半型字

[Implement] TextBox 字串輸入時自動將全形字轉半型字


/// 字串全型與半型轉換
/// </summary>
/// <param name="oriString">被轉換之字串</param>
/// <param name="transType">0 = 半型轉全型, 1 = 全型轉半型</param>
/// <returns></returns>
static public string TransStringType(string oriString, int transType)
{
    string value = string.Empty;

    try
    {
        if (transType != 0 && transType != 1)
        {
            value = oriString;
        }

        if (transType == 0)
        {
            value = Microsoft.VisualBasic.Strings.StrConv(oriString, Microsoft.VisualBasic.VbStrConv.Wide, 0);
        }
        else if (transType == 1)
        {
            value = Microsoft.VisualBasic.Strings.StrConv(oriString, Microsoft.VisualBasic.VbStrConv.Narrow, 0);
        }
    }
    catch (Exception ex)
    {
        value = oriString;
    }

    return value;
}

在 TextChanged Event 中執行全形字轉半型字


{
    string tempString = string.Empty;
    foreach(char str in ((TextBox)sender).Text)
    {
        tempString += iTemUtility.PubFunc.TransStringType(str.ToString(), 1);
    }

     ((TextBox)sender).Text = tempString;
     ((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length;
}

P.S 如需要判斷字串是否為全型字, 方法如下:


/// 檢查是否有全形字
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public static bool isFullWord(string words)
{
    bool result = false;
    string pattern = @"^[\u4E00-\u9fa5]+$";
    foreach (char item in words)
    {
        //以Regex判斷是否為中文字,中文字視為全形
        if (!System.Text.RegularExpressions.Regex.IsMatch(item.ToString(), pattern))
        {
            //以16進位值長度判斷是否為全形字
            if (string.Format("{0:X}", Convert.ToInt32(item)).Length != 2)
            {
                result = true;
                break;
            }
        }
    }
    return result;
}