Auto highlight text in a textbox control - c#

How do you auto highlight text in a textbox control when the control gains focus.

In Windows Forms and WPF:
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;

If you want to do it for your whole WPF application you can do the following:
- In the file App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
//works for tab into textbox
EventManager.RegisterClassHandler(typeof(TextBox),
TextBox.GotFocusEvent,
new RoutedEventHandler(TextBox_GotFocus));
//works for click textbox
EventManager.RegisterClassHandler(typeof(Window),
Window.GotMouseCaptureEvent,
new RoutedEventHandler(Window_MouseCapture));
base.OnStartup(e);
}
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
(sender as TextBox).SelectAll();
}
private void Window_MouseCapture(object sender, RoutedEventArgs e)
{
var textBox = e.OriginalSource as TextBox;
if (textBox != null)
textBox.SelectAll();
}

In ASP.NET:
textbox.Attributes.Add("onfocus","this.select();");

It is very easy to achieve with built in method SelectAll
Simply cou can write this:
txtTextBox.Focus();
txtTextBox.SelectAll();
And everything in textBox will be selected :)

If your intention is to get the text in the textbox highlighted on a mouse click you can make it simple by adding:
this.textBox1.Click += new System.EventHandler(textBox1_Click);
in:
partial class Form1
{
private void InitializeComponent()
{
}
}
where textBox1 is the name of the relevant textbox located in Form1
And then create the method definition:
void textBox1_Click(object sender, System.EventArgs e)
{
textBox1.SelectAll();
}
in:
public partial class Form1 : Form
{
}

I think the easiest way is using TextBox.SelectAll like in an Enter event:
private void TextBox_Enter(object sender, EventArgs e)
{
((TextBox)sender).SelectAll();
}

Here's the code I've been using. It requires adding the attached property to each textbox you wish to auto select. Seeing as I don't want every textbox in my application to do this, this was the best solution to me.
public class AutoSelectAll
{
public static bool GetIsEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsEnabledProperty);
}
public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}
static void ue_Loaded(object sender, RoutedEventArgs e)
{
var ue = sender as FrameworkElement;
if (ue == null)
return;
ue.GotFocus += ue_GotFocus;
ue.GotMouseCapture += ue_GotMouseCapture;
}
private static void ue_Unloaded(object sender, RoutedEventArgs e)
{
var ue = sender as FrameworkElement;
if (ue == null)
return;
//ue.Unloaded -= ue_Unloaded;
ue.GotFocus -= ue_GotFocus;
ue.GotMouseCapture -= ue_GotMouseCapture;
}
static void ue_GotFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox)
{
(sender as TextBox).SelectAll();
}
e.Handled = true;
}
static void ue_GotMouseCapture(object sender, MouseEventArgs e)
{
if (sender is TextBox)
{
(sender as TextBox).SelectAll();
}
e.Handled = true;
}
public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),
typeof(AutoSelectAll), new UIPropertyMetadata(false, IsEnabledChanged));
static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ue = d as FrameworkElement;
if (ue == null)
return;
if ((bool)e.NewValue)
{
ue.Unloaded += ue_Unloaded;
ue.Loaded += ue_Loaded;
}
}
}
The main change I made here was adding a loaded event to many of the examples I've seen. This allows the code to continue working after it's unloaded (ie. a tab is changed). Also I included code to make sure the text gets selected if you click on the textbox with the mouse, and not just keyboard focus it. Note: If you actually click on the text in the textbox, the cursor is inserted between the letters as it should.
You can use this by including the following tag in your xaml.
<TextBox
Text="{Binding Property}"
Library:AutoSelectAll.IsEnabled="True" />

If you need to do this for a large number of textboxes (in Silverlight or WPF), then you can use the technique used in the blog post: http://dnchannel.blogspot.com/2010/01/silverlight-3-auto-select-text-in.html. It uses Attached Properties and Routed Events.

You can use this, pithy. :D
TextBox1.Focus();
TextBox1.Select(0, TextBox1.Text.Length);

If you wanted to only select all the text when the user first clicks in the box, and then let them click in the middle of the text if they want, this is the code I ended up using.
Just handling the FocusEnter event doesn't work, because the Click event comes afterwards, and overrides the selection if you SelectAll() in the Focus event.
private bool isFirstTimeEntering;
private void textBox_Enter(object sender, EventArgs e)
{
isFirstTimeEntering = true;
}
private void textBox_Click(object sender, EventArgs e)
{
switch (isFirstTimeEntering)
{
case true:
isFirstTimeEntering = false;
break;
case false:
return;
}
textBox.SelectAll();
textBox.SelectionStart = 0;
textBox.SelectionLength = textBox.Text.Length;
}

if you want to select all on "On_Enter Event" this won't Help you achieving your goal.
Try using "On_Click Event"
private void textBox_Click(object sender, EventArgs e)
{
textBox.Focus();
textBox.SelectAll();
}

On events "Enter" (for example: press Tab key) or "First Click" all text will be selected. dotNET 4.0
public static class TbHelper
{
// Method for use
public static void SelectAllTextOnEnter(TextBox Tb)
{
Tb.Enter += new EventHandler(Tb_Enter);
Tb.Click += new EventHandler(Tb_Click);
}
private static TextBox LastTb;
private static void Tb_Enter(object sender, EventArgs e)
{
var Tb = (TextBox)sender;
Tb.SelectAll();
LastTb = Tb;
}
private static void Tb_Click(object sender, EventArgs e)
{
var Tb = (TextBox)sender;
if (LastTb == Tb)
{
Tb.SelectAll();
LastTb = null;
}
}
}

I don't know why nobody mentioned that but you can also do this, it works for me
textbox.Select(0, textbox.Text.Length)

textBoxX1.Focus();
this.ActiveControl = textBoxX1;
textBoxX1.SelectAll();

In window form c#. If you use Enter event it will not work. try to use MouseUp event
bool FlagEntered;
private void textBox1_MouseUp(object sender, MouseEventArgs e)
{
if ((sender as TextBox).SelectedText == "" && !FlagEntered)
{
(sender as TextBox).SelectAll();
FlagEntered = true;
}
}
private void textBox1_Leave(object sender, EventArgs e)
{
FlagEntered = false;
}

textbox.Focus();
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;

Related

Apply event format to all textboxes

I have written this code:
private void maskedNASC_KeyDown(object sender, KeyEventArgs e)
{
maskedNASC.BackColor = Color.Aqua;
}
private void maskedNASC_Leave(object sender, EventArgs e)
{
maskedNASC.BackColor = Color.White;
}
I want to apply this property to all the textboxes and masked texts of the form.
I have see many codes like this:
void SetProperty(Control ctr) // resalta textbox onfocus
{
foreach (Control control in ctr.Controls)
{
if (control is TextBox)
{
control.Leave == control.BackColor = Color.Aqua;
control.KeyDown += BackColor = Color.White ;
}
}
}
What is the right way to write this??
Thanks. Alejandro.
I have add this to the form1.designer :
this.maskedNASC.Leave += TextBoxEvent_Leave;
this.maskedNASC.KeyDown += TextBox_KeyDown;
but the code below have an error
[![enter image description here][1]][1]
You can write that in this way
void SetProperty(Control ctr) // resalta textbox onfocus
{
foreach (Control control in ctr.Controls)
{
if (control is TextBox)
{
control.Leave -= control_Leave; //Remove control_Leave if already binded.
control.Leave += control_Leave; //Assigne control_Leave
control.KeyDown -= control_KeyDown ; //Remove control_KeyDown if already binded.
control.KeyDown += control_KeyDown ; //Assigne control_KeyDown
}
}
}
private void control_Leave(object sender, EventArgs e)
{
((Control)sender).BackColor = Color.Aqua;
}
private void control_KeyDown(object sender, KeyEventArgs e)
{
((Control)sender).BackColor = Color.White;
}
You can make the event more general for example (using pattern matching in C# 8.0)
private void TextBoxEvent_Leave(object sender, EventArgs e)
{
if (sender is TextBox bx)
{
bx.BackColor = Color.White;
}
}
private void TextBox_KeyDown(object sender, EventArgs e)
{
if (sender is TextBox bx)
{
bx.BackColor = Color.Red;
}
}
and in the constructor just add
this.maskedNASC.Leave += TextBoxEvent_Leave;
this.maskedNASC.KeyDown += TextBox_KeyDown;
for each text box you have
you can also try the following depending on the C# version you are using
private void TextBoxEvent_Leave(object sender, EventArgs e)
{
if (sender is TextBox)
{
((TextBox)sender).BackColor = Color.White;
}
}
private void TextBox_KeyDown(object sender, EventArgs e)
{
if (sender is TextBox)
{
((TextBox)sender).BackColor = Color.Red;
}
}

How to enable button after all textboxes are not empty in c# winforms?

How can I make button property set to enabled=true after all my textboxes are not empty?
I'm learning programming and my apps are simple.
I know how to enable this property when one of my textboxes have text but this is not the case.
Use case is that user need to put data in both textboxes and after that will be able to click btn.
How in most simple way can I validate all form and then enable button?
There are just 2 tb:
https://i.imgur.com/JUslNWE.png
You need to create a TextBox_TextChanged event and subscribe to all text boxes.
private void TextBox_TextChanged(object sender, EventArgs e)
{
int notEmptyTextBoxCount = 0;
int textBoxCount = 0;
foreach (var item in Controls)
{
if (item is TextBox txtb)
{
textBoxCount++;
if (txtb.Text != String.Empty)
notEmptyTextBoxCount++;
}
}
if (textBoxCount == notEmptyTextBoxCount)
button.Enabled = true;
else
button.Enabled = false;
}
Thanks guys for all feedback.
I have managed to do this this way:
private void ValidateTextBoxes()
{
if (loginTextBox.Text.Length != 0 && passTextBox.Text.Length != 0)
{
generateHashBtn.Enabled = true;
}
else
{
generateHashBtn.Enabled = false;
}
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
ValidateTextBoxes();
}
private void TextBox2_TextChanged(object sender, EventArgs e)
{
ValidateTextBoxes();
}

set different message base on each tab?

how can i show different message box depend on the tab control.
if i click on tab header of xtrapage1 messagebox.show("page1") and if i click on tab header of xtrapage2 messagebox.how("page2")
the code i use was in event mouse down
private void xtraTabControl1_MouseDown(object sender, MouseEventArgs e)
{
DevExpress.XtraTab.ViewInfo.XtraTabHitInfo hi = xtraTabControl1.CalcHitInfo(e.Location);
if (hi.HitTest == DevExpress.XtraTab.ViewInfo.XtraTabHitTest.PageHeader)
{
MessageBox.Show("a");
}
}
it keeps showing "a"
Try this
private void xtraTabControl1_MouseDown(object sender, MouseEventArgs e)
{
DevExpress.XtraTab.ViewInfo.XtraTabHitInfo hi = xtraTabControl1.CalcHitInfo(e.Location);
if (hi.HitTest == DevExpress.XtraTab.ViewInfo.XtraTabHitTest.PageHeader)
{
MessageBox.Show(hi.Page.Text.ToString()) );
if(hi.Page.Name == xtraTabPage1.Text.ToString())
MessageBox.Show("a");
}
}
Try this
if (YourTabControl.SelectedTab.Name == "tabName" )
{
// do stuff
}
Or you can achieve the same functionality on selectedIndexChanged event of tab.
private void YourTabControl_SelectedIndexChanged(object sender, EventArgs e)
{
if (YourTabControl.SelectedTab == YourTabControl.TabPages["YourTabName"])
{
// your matched condition.
}
}

Double Click on label open Form C#

Im trying to open a new form when a label is double clicked. Im able to drag and drop the label .Im trying to open a new form on double click of label now.
private void control_MouseDown(object sender, MouseEventArgs e)
{
var control = sender as Control;
this.DoDragDrop(control.Name, DragDropEffects.Move);
}
private void control_DoubleClick(object sender, EventArgs e)
{
frm = new Frm();
frm.ShowDialog();
frm.Dispose();
}
EDIT 1:
I have tried both possible answers below, and they have not worked for me?
A more cleaner way is (note I changed Frm to Form1):
private void control_DoubleClick(object sender, EventArgs e)
{
using (Form1 frm = new Form1())
{
frm.ShowDialog();
}
}
You can't add DragDrop on MouseDown and then DoubleClick. That won't work.
I don't think there's an easy way to get around that, but once a control is being dragged, it won't respond to double click messages.
I've made some quick tests, and there's a "hacky" way. It'll make your dragging look weird (since it'll start after some time, instead of immediately after you press the mouse button), but here it goes:
private bool _willDrag = false;
private bool control_MouseUp(object sender, MouseEventArgs e)
{
// disable dragging if we release the mouse button
_willDrag = false;
}
private bool control_DoubleClick(object sender, EventArgs e)
{
// disable dragging also if we double-click
_willDrag = false;
// .. the rest of your doubleclick event ...
}
private void control_MouseDown(object sender, MouseEventArgs e)
{
var control = sender as Control;
if (control == null)
return;
_willDrag = true;
var t = new System.Threading.Timer(s =>
{
var callingControl = s as Control;
if (callingControl == null)
return;
// if we released the mouse button or double-clicked, don't drag
if(!_willDrag)
return;
_willDrag = false;
Action x = () => DoDragDrop(callingControl.Name, DragDropEffects.Move);
if (control.InvokeRequired)
control.Invoke(x);
else
x();
}, control, SystemInformation.DoubleClickTime, Timeout.Infinite);
}
In the form.Designer right click on your label then properties, in the properties window click in events (the thunder icon), in the double_Click event dropdown select the event handler (control_DoubleClick) this method must have two parameters an object and a eventArgs
This is tricky as the DoDragDrop will eat up any further mouse events, and MSDN posting a rather stupid example doesn't help much.
Solution: Do not start the D&D in the MouseDown if you want to still receive click or double click events but use the MouseMove instead:
Replace this
private void control_MouseDown(object sender, MouseEventArgs e)
{
var control = sender as Control;
this.DoDragDrop(control.Name, DragDropEffects.Move);
}
by this:
private void control_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
DoDragDrop((sender as Control), DragDropEffects.Move);
}
Don't forget to hook up the new event!

Make code for multiple textbox when press Enter send command Tab better

i already have code when user press key Enter on keyboard, it return tab and "jump" to next field, its working great, its possible make it for 2 or 3 textbox, problem when need make it on multiple textbox like 20 textbox for each form, its just not work.
See code:
// Detect if Enter key is pressed on each text box, mute sound enter "ding" sound and replace Enter for tab (problem that have make it for each textbox)
private void txtAltura_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true; //Silenciar Enter
SendKeys.Send("{TAB}");
}
}
private void txtLargura_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true; //Silenciar Enter
SendKeys.Send("{TAB}");
}
}
private void txtProfundidade_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true; //Silenciar Enter
SendKeys.Send("{TAB}");
}
}
//execute keypress command when enter is typed on textbox
private void txtProfundidade_TextChanged(object sender, EventArgs e)
{
if (txtProfundidade.Text != "") { foreach (char c in txtProfundidade.Text.ToCharArray()) txtProfundidade_KeyPress(sender, new KeyPressEventArgs(c)); }
}
private void txtLargura_TextChanged(object sender, EventArgs e)
{
if (txtLargura.Text != "") { foreach (char c in txtLargura.Text.ToCharArray()) txtLargura_KeyPress(sender, new KeyPressEventArgs(c)); }
}
private void txtAltura_TextChanged(object sender, EventArgs e)
{
if (txtAltura.Text != ""){foreach (char c in txtAltura.Text.ToCharArray()) txtAltura_KeyPress(sender, new KeyPressEventArgs(c));}
}
Hope make it better.
Thanks in advance..
if its windows form app can use this, this will replace tab key press with Enter key
protected override bool ProcessKeyPreview(ref Message m)
{
if (m.Msg == 0x0100 && (int)m.WParam == 13)
{
this.ProcessTabKey(true);
}
return base.ProcessKeyPreview(ref m);
}
From what I understand, you're trying to figure out a way to assign event handlers to multiple textbox controls and don't want to write a handler for each one. If that's the case, try this:
private void Form1_Load(object sender, EventArgs e)
{
foreach (TextBox textBox in this.Controls.OfType<TextBox>())
{
textBox.KeyDown += new KeyEventHandler(textBox_KeyDown);
}
}
void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
SendKeys.Send("{TAB}");
}
}
This will assign a handler to each textbox control on the form.
That worked perfectly well.
I also have to repeat this on each textbox to check if all codes was filled and update statusbar:
private void txtAltura_TextChanged(object sender, EventArgs e)
{
testePreenchidoecalculo();
}
private void txtLargura_TextChanged(object sender, EventArgs e)
{
testePreenchidoecalculo();
}
private void txtProfundidade_TextChanged(object sender, EventArgs e)
{
testePreenchidoecalculo();
}
Its possible to make it better ?

Categories

Resources