Custom TextBox Control that Switches Keyboard Lang

2019-08-07 01:37发布

问题:

i need to make something like that http://www.codeproject.com/Articles/301832/Custom-Text-box-Control-that-Switch-keyboard-langu but for WPF and C#

i'v tried to do it with a simple if statement but i was have to put another textbox like that

    private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
    {
        textBox1.Focus();
        if (textBox1.Text == "Q" || textBox1.Text == "q")
        {
            textBox2.Text = textBox2.Text+ "ض";
            textBox1.Text = "";
        }
        else if (textBox1.Text == "W" || textBox1.Text == "w")
        {
            textBox2.Text = textBox2.Text + "ص";
            textBox1.Text = "";
        }
        // and so ..
    }

it works but i want to do something like the link above

回答1:

You can do that in WPF by creating a new custom Control that inherits TextBox. In that Create a new TextLanguage Property and Override the OnKeyDown method

namespace WpfApplication
{
    public enum TextLanguage
    {
        English,
        Arabic
    }

    public class CustomTextBox : TextBox
    {        
        public TextLanguage TextLanguage { get; set; }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (TextLanguage != WpfApplication.TextLanguage.English)
            {
                e.Handled = true;
                if (Keyboard.Modifiers == ModifierKeys.Shift)
                {
                    // Shift key is down
                    switch (e.Key)
                    {
                        case Key.Q:
                            AddChars("ص");
                            break;
                        // Handle Other Cases too
                        default:
                            e.Handled = false;
                            break;
                    }
                }
                else if (Keyboard.Modifiers == ModifierKeys.None)
                {
                    switch (e.Key)
                    {
                        case Key.Q:
                            AddChars("ض");
                            break;
                        // Handle Other Cases too
                        default:
                            e.Handled = false;
                            break;
                    }
                }
            }
            base.OnKeyDown(e);
        }

        void AddChars(string str)
        {
            if (SelectedText.Length == 0)
                AppendText(str);
            else
                SelectedText = str;

            this.SelectionLength = 0;
            this.CaretIndex = Text.Length;

        }
    }
}