Set Focus to TextBox : Focus « Windows Presentation Foundation « C# / CSharp Tutorial






using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

    public class NavigateTheWeb : Window
    {
        Frame frm = new Frame();
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new NavigateTheWeb());
        }
        public NavigateTheWeb()
        {
            Content = frm;
            Loaded += OnWindowLoaded;
        }
        void OnWindowLoaded(object sender, RoutedEventArgs args)
        {
            UriDialog dlg = new UriDialog();
            dlg.Owner = this;
            dlg.Text = "http://";
            dlg.ShowDialog();

            try
            {
                frm.Source = new Uri(dlg.Text);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, Title);
            }
        }
    }
    class UriDialog : Window
    {
        TextBox txtbox = new TextBox();
        public UriDialog()
        {
            ShowInTaskbar = false;
            SizeToContent = SizeToContent.WidthAndHeight;
            WindowStyle = WindowStyle.ToolWindow;
            WindowStartupLocation = WindowStartupLocation.CenterOwner;
            
            txtbox.Margin = new Thickness(4);
            Content = txtbox;
            txtbox.Focus();
        }
        public string Text
        {
            set
            {
                txtbox.Text = value;
                txtbox.SelectionStart = txtbox.Text.Length;
            }
            get
            {
                return txtbox.Text;
            }
        }
        protected override void OnKeyDown(KeyEventArgs args)
        {
            if (args.Key == Key.Enter)
                Close();
        }
    }








24.165.Focus
24.165.1.Fire an event when an element gains and loses focus.Fire an event when an element gains and loses focus.
24.165.2.Focus a TextBox
24.165.3.Set Focus to TextBox