On leaving a control, how can I give that control focus again? - c#

I've got TextBoxes in a C# form. The user enters data, and then when they leave the control (almost always by hitting Tab), I check the data to make sure it's valid. If it is invalid, I want to highlight their text so they can immediately fix it rather than having to click it.
Right now, on Control.Leave, I validate their entry. This works just fine. However, since they hit Tab, right after they dismiss the error message, it goes on to the next object, even though I've got ((TextBox)sender).Focus();
How can I have the above line fire after the form Tabs to the next control.

You may want to look into Control.CausesValidation property
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.causesvalidation(v=vs.110).aspx
You can validate the control prior to the user leaving focus rather than waiting on Focus moving itself.
And here's MSDN documentation for Control.Validating event, does a good job at laying out the sequence of events when gaining / losing focus of a Control.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating(v=vs.110).aspx
Notice how Control.Validating and Control.Validated are launched prior to Control.LostFocus. You can perform your validation step prior to allowing the user to lose focus of your Textbox.
There's also a pretty good previous answer on stackoverflow.com which outlines how to do this: C# Validating input for textbox on winforms

If you handle the Control.Validating event, setting e.Cancel to true will stop the change of focus from occurring.
Note that this method will also stop buttons from working, so you may need to set Control.CausesValidation to false on certain buttons.
You will also need the following snippet on the main form to allow the close button to work:
protected override void OnFormClosing(FormClosingEventArgs e) {
e.Cancel = false;
base.OnFormClosing(e);
}

Try using the LostFocus event on the TextBox to Focus it again

Related

How to set focus back to form, after button is pressed

I am making a game, and to open up and close the store, you press S. While in the store, you have six different choices to buy from, but they are all buttons.
However, once you buy something, the focus is no longer on the form, but on the button, and the key down event is part of the form, therefore, because the focus gets switched from the form to the button, the key down event no longer works, and disables you from closing the store and continuing on with the game.
My question is how to set the focus back to a form once a button is press? I started out with visual basic, and the code would be something along the lines of form1.setfocus, but its totally different in c#.
I have tried Activating the form, .focus, a lot, and nothing seems to be setting the focus back to the form. Help would be greatly appreciated.
Form1.focus();
But I think, to get keyboard events on Form itself, you need KeyPreview set to true for the Form so that Form gets Keys first and then other controls.
Try:
form.Focus();
MSDN:
The Focus method returns true if the control successfully received input focus. The control can have the input focus while not displaying any visual cues of having the focus. This behavior is primarily observed by the nonselectable controls listed below, or any controls derived from them.
Tell me more
You can add the key down event to the buttons too.

How to change default behaviour that a textbox loses focus on back button pressed

The default behaviour of pressing back button when a textbox is on focus is that the virtual keyboard closes and the textbox loses focus. And the user press back key again, the window goes back to previous window.
However, I want the change this behavior. I want the window to go back to previous window directly when the back key is pressed, ignoring whether the textbox is on focus or not.
I tried the following methods,
Use HardwareButtons.BackPressed event, doesn't work (maybe it only works for Direct3D, I am not sure). The event isn't fired during back button pressed.
Use Textbox_onKeyUp, doesn't work. The event isn't fired during back button is up.
Use override void OnBackKeyPress, doesn't work. It does fire as expected during other cases, but during the situation when the textbox is from on focus to losing focus (the keyboard closes), the event isn't fired.
Use Textbox_OnLoseFocus, works fine but need a lot of condition checks because some times losing focus doesn't mean that I want to go back to previous page.
Please help. Thanks.
Finally I didn't change the behaviour, made a different design. But I still think that in that case, the Nokia's behaviour is most user-friendly.

How to disable the selection on a TextBox

I want to disable selecting text and clicking in the middle of text in a TextBox, but the user must be able to enter this TextBox and write at the end of earlier text, so I cannot make it ReadOnly or Enable = false.
I try to handle MouseDown and do the following:
input.Select(input.Text.Length, 0);
It helps with placing a cursor in the middle of text, but the user still can make a selection from the end.
I also make a MessageBox() on MouseDown event, but in this case the user cannot click on textBox and write anything.
The last try was to set a focus() in another Control and focus back, after a period of time, but it didn't work at all. User still can make a selection.
How can I do it?
How about this for Click event
Edit: Also do the same for DoubleClick and MouseLeave to cover all cases. You can have a common event handler.
private void textBox1_Click(object sender, EventArgs e)
{
((TextBox) sender).SelectionLength = 0;
}
If it fits the UI/user model, another approach is to use two text boxes: a read-only one with the previous text that the user can see and act on (if that is something he needs to do) and an editable one for the new text along with a button to commit the new text to the read-only text box (and persistence layer).
That approach is not only arguably more user-friendly—the editable box is completely editable rather than just "appendable", which gets confusing when the user hits Backspace—but also requires less fighting with the framework to make the boxes do what you need.
You're not far off with your MouseDown event handler, but probably better to catch MouseUp, as this is the event that will fire when they have finished selecting.
Alternatively, you could catch the SelectionChanged event.
Just put your:
input.Select(input.Text.Length, 0);
code in any of those event handlers.

How do I prevent a tab from rendering when selected?

I would like to be able to have a user be able run through the tabs, setting focus to each one, but only when they hit enter, the tabpage will render.
You would think that the paint event would be involved, but I don't know how to "cancel out" of it, if that would even do the job..
First, I should caution you that you're overriding the standard Windows behavior. In any property page dialog or anywhere else that uses tabs in the user interface, using the left and right arrow keys will flip through the tabs and cause them to display their contents in the tab control. You do not have to press Enter to get the selected tab page to display. Make sure that your users understand that your application is different (and that you understand the needs of your users) if you decide to go this route.
That said, you can override this behavior by handling the KeyDown event for the TabControl, detecting when one of the arrow keys has been pressed, and cancelling it. For example:
private void myTabControl_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
//Check to see if an arrow key was pressed
if ((e.KeyCode == Keys.Left) || (e.KeyCode == Keys.Right))
{
//Cancel the keypress by indicating it was handled
e.Handled = true;
}
}
However, once you do this, there will be no way for the user to set focus to a particular tab page's tab, because once the tab gets focus, the tab page is immediately brought into view. This is handled by the parent TabControl and is unrelated to the Paint event (which is responsible for how the control gets painted, not when or why).
Of course, you can always determine if the Enter key was pressed in the same KeyDown event and activate any tab page that you wish (such as by using a counter variable that is incremented/ decremented each time the corresponding arrow key is pressed), but there will be no visible indication to the user which tab will then be brought into view. The focus rectangle will not be drawn.
Also be aware that pressing Ctrl+Tab or Ctrl+Page Up/Page Down will switch between tab pages. If this is also undesirable, you'll need to watch for and cancel these key combinations as well.Any time you start trying to override default behaviors, you're in for a lot more trouble than if you just design your application around it. If there's a particular reason you want to require the Enter key to commit tab page switching, we might be able to help you come up with an easier and better solution.
I'm not sure I understand what you are trying to accomplish, but it sounds like you can do it using the Visible property.
You should be able to set the TabPage's visibility to false when the user switches to it, and then set it to true only when you want to.

Toolstripbutton not validating textbox

I have a textbox, a standard button and a toolstrip containing a couple of buttons.
In the validating event of the textbox I coded to check whether it is blank.
If yes then it shows a message 'Enter Value'. When the standard button is clicked while
the textbox is empty, it's validating properly and showing the message but when the
toolstripbutton is clicked it's not validating the textbox and no message is shown. It seems that I've got to write the validation code explicitly in the
toolstripbutton_click event which is too troublesome when there are multiple textboxes and toolstripbuttons on a single form.
What I want to know is whether the textbox_validating can be fired when the toolstripbutton is clicked? Handling toolstrips is really a headache.
The ToolStripItem classes are special, they don't derive from Control. One side-effect of that is that they don't take the focus away from the active control. And that prevents the Validating event from firing.
Several things you can do. You could call the textbox' parent's ValidateChildren() method. Or you could move the focus yourself:
private void toolStripButton1_Click(object sender, EventArgs e) {
btnSave.Focus();
if (btnSave.Focused) btnSave.PerformClick();
}
Write the following in toolstripbutton click event:
Me.Validate()
You can call the textbox_validating procedure from the procedure that handles the toolstripbutton click event, but you may have to add some logic to see if it passed validation before proceeding with the rest of the toolstripbutton_click event. Since you said you have a lot of textboxes to validate, you might want to consider making a Validate() function that returns true or false and checks all of the textboxes. Then all you have to do is check if Validate() = true and call the same function from all of your toolstrip buttons instead of copying the same code over and over again.

Categories