TextBox took back focus while other controls don't - c#

I wanted to focus to a TextBox when I leave an other TextBox.
Let's say I have 3 textboxes. The focus is in the first one, and when I click into the second one, I want to put the focus into the last one instead.
I subscribed to the first textbox's Leave event and tried to focus to the third textbox like: third.Focus(). It gains focus for a moment but then the second one got it eventually (the one I clicked).
Strangely if I replace the second TextBox to a MaskedTextBox (or to any other control), the focus remains on the third one.
Pressing Tab does work though.
These are plain textboxes right from the toolbox.
What is the reason, how can I solve this?

Try to handle Enter event of the textBox2. (In properties window double click on Enter event)
//From Form1.Designer.cs
this.textBox2.Enter += new System.EventHandler(this.textBox2_Enter);
private void textBox2_Enter(object sender, EventArgs e)
{
textBox3.Focus();
}
EDIT:
This code looks very strange, but it works for me. According to this post HERE I use ActiveControl property instead of Focus() method. But behavior of TextBox is very strange because it try to be focused multiple times.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
foreach (Control control in Controls)
{
control.LostFocus += (s, e) => Console.WriteLine(control.Name + " LostFocus");
control.GotFocus += (s, e) =>
{
Console.WriteLine(control.Name + " GotFocus");
if (!requestedFocusToTextBox2) return;
ActiveControl = textBox2; //textBox2.Focus() doesn't work
requestedFocusToTextBox2 = false;
};
}
}
private bool requestedFocusToTextBox2;
private void textBox1_Leave(object sender, EventArgs e)
{
ActiveControl = textBox2;
requestedFocusToTextBox2 = true;
}
}

Related

Why I can not change focus?

Im making a calculator.and for the buttons that type numbers, I wrote a condition that if the focus was on text box 1, it would enter the text there, if not, it would enter text box 2. But unfortunately the code does not work and I dont understand the problem.
(WindosForm(.Net framework))
if (textBox1.Focus() == true)
{
textBox1.Text = textBox1.Text + "1";
}
else
{
textBox2.Text = textBox2.Text + "1";
}
Subscribe to "Enter" event for your two textbox and save it. Use the same method for the two textboxes.
TextBox focusedTB;
private void textBox_Enter(object sender, EventArgs e)
{
focusedTB = sender as TextBox;
}
...
this.textBox1.Enter += new System.EventHandler(this.textBox_Enter);
...
this.textBox2.Enter += new System.EventHandler(this.textBox_Enter);
Now you know the last textbox that got focus.
private void button1_Click(object sender, EventArgs e)
{
focusedTB.Text += "1";
}
Your code appears to be attempting to check if the control is focused. The correct way to do that is:
if (textBox1.Focused)
{
// Because 'Focused' is a property. 'Focus()' is a method.
textBox1.Text = textBox1.Text + "1";
}
.
.
.
The answer to your question Why I can not change focus? is that textBox1 receives the focus every time you call this:
if (textBox1.Focus())
As mentioned in one of the comments, here's how the Focus method works:
// Summary:
// Sets input focus to the control.
//
// Returns:
// true if the input focus request was successful; otherwise, false.
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool Focus();
Note: This is a copy-paste of metadata that you can look at by right-clicking over Focus() in your code and selecting Go to Definition then expanding the definition.
I think you talk about Windows Form ?
You cannot manage like this but use event "Enter" of your textboxes, when you click inside the textbox, you give the focus to this textbox and you can do anything inside. Here I put the right focuses TextBox in a variable.
private TextBox _textBoxFocused; //this is always the righ TextBox
private void textBox1_Enter(object sender, EventArgs e)
{
_textBoxFocused = textBox1;
}
private void textBox2_Enter(object sender, EventArgs e)
{
_textBoxFocused = textBox2;
}

How to get numericupdown control to pass its value to a another control as I am typing not by having to hit Enter or click on another control

I have several numericupdown controls on a Winform. I have all the NUDs on the form coded to summarize all the NUDs inside a textbox. My issue is not with that, that happens perfectly. My issue is, that in order for the value from any of the NUDs to summarize inside the texbox, I have to either press enter or click inside any other NUD. Clicking on Tab will not work. I want the value inside the texbox to be updated as I type inside any of the NUDS, without having to press enter or give focus to another NUD. How can I do that? By the way, I've placed the code to summarize all the NUDs inside the ValueChanged event of each NUD. This is the code I have placed inside each NUD ValueChanged Event. Thank you
private void NudNumberOne_ValueChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(NudNumberOne.Text) && !string.IsNullOrEmpty(NudNumberTwo.Text) && !string.IsNullOrEmpty(NudNumberThree.Text))
textBox1.Text = (double.Parse(NudNumberOne.Text) + double.Parse(NudNumberTwo.Text) + double.Parse(NudNumberThree.Text)).ToString();
}
The ValueChanged() event doesn't fire until the Text value has been parsed successfully into a numeric value and assigned to the NumericUpDown control. You've already found that this doesn't happen until you hit Enter or change controls.
The NumericUpDown doesn't expose a TextChanged() event...but it's easy enough to cast it back to Control and wire it up that way. Just do this in the Load() event of your Form:
private void Form1_Load(object sender, EventArgs e)
{
((Control)NudNumberOne).TextChanged += Ctl_TextChanged;
((Control)NudNumberTwo).TextChanged += Ctl_TextChanged;
((Control)NudNumberThree).TextChanged += Ctl_TextChanged;
}
private void Ctl_TextChanged(object sender, EventArgs e)
{
try
{
textBox1.Text = (double.Parse(NudNumberOne.Text) + double.Parse(NudNumberTwo.Text) + double.Parse(NudNumberThree.Text)).ToString();
} catch (Exception ex) {
textBox1.Text = "";
}
}

Prevent selecting text in a TextBox

Similar questions have been already asked (e.g., here), however I've not found an answer for my specific case. I'm building a custom control based on a DevExpress control, which in turns is based on standard TextBox and I've a flickering problem that seems due to the base TextBox component, which tries to update selection.
Without explaining all the details of my custom control, to reproduce the problem you just need to place a TextBox inside a Form and then use this code:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
textBox1.MouseMove += TextBox1_MouseMove;
}
private void TextBox1_MouseMove(object sender, MouseEventArgs e) {
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
}
}
If you launch it, you click on the TextBox and then you move the cursor toward right you will notice the flickering problem (see video here). For my custom control I would need to avoid this flickering. I'm bound to use a TextBox (so no RichTextBox). Any idea?
The solution has been provided in the meantime by Reza Aghaei by overriding WndProc and intercepting WM_SETFOCUS messages. See here
Depending on what u want to do there are several solutions:
If you want to prevent the selection it would be:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
(sender as TextBox).SelectionLength = 0;
}
Or for selecting all:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
(sender as TextBox).SelectAll();
}
And besides that u also could specify the conditions for selecting, for example:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
if (MouseButtons == MouseButtons.Left) (sender as TextBox).SelectAll();
else (sender as TextBox).SelectionLength = 0;
}
But as long as you want to select the text you always will get some flickering, because a normal Textbox has not the possibility to use things like BeginEdit and EndEdit and so it will change the text first and then select it.
Looking at the video it looks like your textbox is calling WM_ERASEBKGND unnecessarily. In order to remedy this problem you can subclass the textbox class and intercept these messages. Below is sample code which should do the trick (untested) Disclaimer: I have used this technique for other WinForm controls that had the type of flicker shown in your video but not TextBox. If it does work for you, please let me know. Good luck!
// textbox no flicker
public partial class TexttBoxNF : TextBox
{
public TexttBoxNF()
{
}
public TexttBoxNF(IContainer container)
{
container.Add(this);
InitializeComponent();
//Activate double buffering
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
//Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
}
//http://stackoverflow.com/questions/442817/c-sharp-flickering-listview-on-update
protected override void OnNotifyMessage(Message m)
{
//Filter out the WM_ERASEBKGND message
if (m.Msg != 0x14)
{
base.OnNotifyMessage(m);
}
}
}

issue with textbox event handlers

I am still learning how to do with event handler. What I want is: When I click the txtMonday to get focused, then I click the remove button to clear this selected textbox. Problem is: when I click the remove button for the selected textbox, all the unselected textboxes are clear. I only want to remove the selected textbox. How to solve this problem? Your code example much appreciated. Thanks! I am using WPF and C#.
private void btnRemoveClick(object sender, RoutedEventArgs e)
{
TextBox text = new TextBox();
text.GotFocus += new RoutedEventHandler(txtMonday_GotFocus);
txtMonday.Clear();
text.GotFocus += new RoutedEventHandler(txtTuesday_GotFocus);
txtTuesday.Clear();
}
private void txtMonday_GotFocus(object sender, RoutedEventArgs e)
{
}
private void txtTuesday_GotFocus(object sender, RoutedEventArgs e)
{
}
This should do what you want. I suggest you do some more studying about C# though, as your code shows some fundamental misunderstandings.
//you'll need a variable to store the last focused textbox.
TextBox txtLast;
public MainWindow()
{
InitializeComponent();
//add an event for all the textboxes so that you can track when one of them gets focus.
txtSunday.GotFocus += txt_GotFocus;
txtMonday.GotFocus += txt_GotFocus;
txtTuesday.GotFocus += txt_GotFocus;
txtWednesday.GotFocus += txt_GotFocus;
txtThursday.GotFocus += txt_GotFocus;
txtFriday.GotFocus += txt_GotFocus;
txtSaturday.GotFocus += txt_GotFocus;
//default to clearing sunday to avoid exception
//you could also let it clear a new TextBox(), but this is wasteful. Ideally,
//you would handle this case gracefully with an if statement, but I will leave that
//as an exercise to the reader.
txtLast = txtSunday;
}
private void txt_GotFocus(object sender, RoutedEventArgs e)
{
//whenever you click a textbox, this event gets called.
//e.source is the textbox, but since it is is just an "Object" we need to cast it to a TextBox
txtLast = e.Source as TextBox;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//this will clear the textbox which last had focus. If you click a button, the current textbox loses focus.
txtLast.Clear();
}

Windows Forms - get Text value from object of type button

I have a Windows form named Form1 and panel within this form named panel1. I use the panel only to place buttons there so that I can group them and work with them separately from the other buttons in my Form1. For the purpose of my program I need to handle every button click made from the buttons inside panel1. For this purpose I use the same code snippet:
public Form1()
{
InitializeComponent();
// Set a click event handler for the button in the panel
foreach (var button in panel1.Controls.OfType<Button>())
{
button.Click += HandleClick;
}
}
What I need to do is to have a way to identify which button exactly has been clicked. For this purpose I played a little bit with my handler method:
private void HandleClick(object o, EventArgs e)
{
MessageBox.Show("HI" + o.ToString());
}
which gave me some hope because I get this:
It's the second part - Text: button4 which is actually enough information to continue with my work. But I can't find a way to get this piece of information without some complicated string manipulations. So is there a way to get this or other unique information about the button been clicked given the way I have written my code?
private void HandleClick(object sender, EventArgs e)
{
var btn = sender as Button;
if (btn != null)
{
MessageBox.Show(btn.Text);
}
}
One option is to cast the object to a Button, but rather than doing the casting you can change how the event handler is assigned so that you don't need to cast in the first place:
foreach (var button in panel1.Controls.OfType<Button>())
{
button.Click += (_,args)=> HandleClick(button, args);
}
Then just change the signature of HandleClick to:
private void HandleClick(Button button, EventArgs e);
You need to cast sender to the Button class so you can access its properties:
Button b = (Button)sender;
MessageBox.Show(b.Text);

Categories

Resources