1. 程式人生 > >WPF模擬鍵盤輸入和刪除

WPF模擬鍵盤輸入和刪除

private void ButtonNumber_Click(object sender, RoutedEventArgs e)
{
    Button btn = (Button)sender;
    string number = btn.Content.ToString();
    string keyword = txtKeyword.Text;

    //已經存在點"."
    if (keyword.Contains(".") && number.Equals("."))
    {
        txtKeyword.Focus();
        return;
    }
    //當前焦點位置
    int start = txtKeyword.SelectionStart;
    //焦點後面新增內容
    if (Common.Utils.isNumber(number) || number.Equals("."))
    {
        txtKeyword.Text = keyword.Insert(start, number);                
        txtKeyword.SelectionStart = (start + number.Length);
    }
    else
    {
        //刪除焦點前面的內容
        if (start > 0)
        {
            txtKeyword.Text = txtKeyword.Text.Remove(start - 1, 1);
            txtKeyword.SelectionStart = start - 1;
        }
    }
    txtKeyword.Focus();
}