Mega Code Archive

 
Categories / C# Tutorial / WPF
 

Set Focus to TextBox

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();         }     }