Bring cursor to a textbox in C# - c#

I want to bring the cursor to a textbox when i clicked a button. How can i do that? I tried Focus() method but it didn't not work. The code is shown below.
CsNIPAddrTextBox.Focus();
CsNIPAddrTextBox.TabIndex = 1;

Try textbox1.select(). It's the best approach to bring your cursor to your textbox. It also selects content of the texbox which makes it easier for the user to edit what's inside the textbox.

If that's a 'proper' TextBox (i.e. not custom) then simply calling Focus() should work. It might not, however, if it's read-only (I'm not sure - I've not tried. I know you can get a caret in a read-only box, which implies it can get focus). Certainly if it's not Enabled then you won't be able to set focus.
Check the CanFocus property is true - if it's not, then there might be some other reason preventing the control from receiving focus.
If that's true, however, and the caret still doesn't make it to the control - you need to verify that it is receiving it. Add an event handler for the text box's GotFocus event and breakpoint it to clarify that it gets hit. My guess is that it your breakpoint will be hit. If so - then the answer is that another process is setting focus to another control immediately after your button click occurs. For example, if you do this kind of thing in a validation event handler you'll get a similar result, because the Windows Forms pipeline is already in the process of changing controls when the handler is fired.
Also - why are you setting TabIndex=1? Generally TabIndex is set at design time and left alone (unless of course these are dynamically created). Unless you have a particular reason for doing this I'd get rid of that line. It doesn't have a bearing on why this would/wouldn't work - just an observation.

Edit again:
If you try to select a TextBox in the Click event of a TreeView, it usually fails, because after the Click event the TreeNode will be selected, making your previous Focus() or Select() useless. The workable way is, perhaps, calling them in a Timer.
Timer t = new Timer();
t.Interval = 10;
t.Tick += new EventHandler((s,ev)=>textBox2.Focus());
t.Start();
This is more like a hack though...

Set theActiveControl property of the form
ActiveControl = yourtextbox

You have to use TextBox.Select Method
For example
textbox1.Select(textbox1.Text.Length,0);
Sets the cursor to the end of the text in yout textbox.

If i read right you are talking about moving mouse cursor to the textbox? - Then you can use code like this:
System.Windows.Forms.Cursor.Position =
PointToScreen(
new Point( textBox1.Location.X + 5, textBox1.Location.Y + 5)
);

I know many of you had provided answers, but this may be useful to some who weren't able to get from previous responses.
This worked for me, setting Select() on input text had set the cursor to the textbox.
Have this in form constructor:
this.Activated += OnActivated;
Handler Code:
private void OnActivated(object sender, EventArgs eventArgs)
{
txtUser.Select();
}

if textbox.Multiline=true and/or textbox.WordWrap = true, the cursor might be hiding at the bottom of the field.

Related

C#: KeyDown Event does not work in controls

I am trying to finish my final school project. I am creating a c# winform game to be specific. We can not use anything else.
I will not be posting here code because I got it pretty messed up and I guess u can answer me just with this info.
Setup:
I got my program set up like this. The is main form and two user controls. I switch those controls within the main form during the game. The first one is MENU and the second one is GUI with picturebox acting as a gamescene.
Problem:
Setup quite not important I guess. But what I need to do is to do some action when I press key Down on the first Control (while it is active in the form). Sounds easy I thought at first but the onKeyDown event in the menu.cs(1st usercontrol) is doing nothing when i press the key(The event method is not blank). I tried this.previewKey = true; in the menu load method but it did not even recognize it.
So my question is: Is there any way to use onKeyDown in usercontrols code?
I did it this way becouse I use the same keys in the second controls and i didnt want it to get messy (which obviously did the oposite huh)
TLDR: Need to use onKeyDown event in userControls (keyPreview might be the key)
BONUS
I also need to somehow link variables from Controls 1 to Form and Controls 2.
I looked it up and found out it would be easy in situacion like "Form to Form" but since it is userControls I cant figure it out and I feel like I am just a tiny bit from finishing it.(feels terrible sitting here 9 hours xD please help)
On the keypress event make sure it is for the selected control an not the main form. If you are capturing for the form to determine which key was pressed then use the keypress event for that. You can use a messagebox to verify that you have the right control. Every key has an integer value and you can access and use those by using the properties of e.
Bonus. Depending on how you implemented your code you will have to use either global varibles to pass the data across the forms or use delegates to actively access and set controls on another form
You have to register the event in the Form.Designer.cs :
private void InitializeComponent()
{
// Your form properties here
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
}
You're KeyDown event can be used like this in the Form.cs code :
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// To know if your event is working and the value of the key who's pressed
MessageBox.Show("Key Pressed = "
+ e.KeyCode.ToString()
+ ", Value = "
+ e.KeyValue.ToString());
// Example - add some actions bellow
if (e.KeyValue == 13)
MessageBox.Show("Return Key Pressed");
}

Win32Exception - error creating window handle?

Can you explain why this happens? Here are steps to reproduce the exception:
Drag-n-drop a TextBox on a form. Add any other focusable control such as a button on the form.
Add 2 event handlers for that TextBox as follow:
private void textBox_GotFocus(object sender, EventArgs e){
((TextBox)sender).HideSelection = false; //<-- exception highlighted at here.
}
private void textBox_LostFocus(object sender, EventArgs e){
((TextBox)sender).HideSelection = true;
}
Run the form and first click on the textBox, then click on the button then click on the textBox again, and the exception will throw: "Win32Exception - error creating window handle".
The code is simply to make the HideSelection change accordingly when the textBox gets focused and loses focus.
UPDATE
I don't know why is so volatile, I created another project and now the problem is different, there is no exception but an indefinite loop which makes the textbox flicker, the form doesn't seem to responsive, the CPU usage is consumed up to about 17-20%. The last demo is still opened and that demo still has the Win32Exception thrown. Not a clue at all. Now the code of the two projects are the same but the problems are different.
Well, there are a couple of things to note.
First of all, HideSelection doesn't hide or unhide the selection. It specifies, whether the selection will be hidden (or not) when the control loses focus. So it's pointless to change it when the TextBox becomes focus'ed.
What you're doing in LostFocus is default, btw. Why there is an exception in GotFocus is burried within Windows API, I guess. Maybe some undefined state when HideSelection checks inside a focus changed event whether the TextBox has focus or not or tries to hide the selection which is not shown.
Edit: It's not the Windows API on the first hand, but the framework. It tries to "recreate the handle" in the setter of HideSelection if it is changed (don't know why yet - would have to analyse sources) and seems to fail (don't know why either).
Edit2: Finally there's some problem in Win32 DestroyWindow - which leads to skipping the creation of the new window. Maybe because the old one is "in use" in the focus change events?
Interestingly, as soon as the exception occurs (for me), the LostFocus event is fired, immediately followed by GotFocus which throws another exception a.s.o. thus blocking the GUI. Both assignments to HideSelection throw the exception.
Also, when you click the TextBox, any selection is deselected automatically. This, however, is not the reason for the problem, because the exception is thrown if you change focus by pressing Tab (whose normal behaviour is to restore focus). But it may be related (state problems).
If you actually want to restore the selection, you could do it like this:
int selStart;
int selLen;
void textBox1_LostFocus(object sender, EventArgs e)
{
selStart = textBox1.SelectionStart;
selLen = textBox1.SelectionLength;
}
void textBox1_GotFocus(object sender, EventArgs e)
{
BeginInvoke((Action)(() =>
{
textBox1.SelectionStart = selStart;
textBox1.SelectionLength = selLen;
}));
}
I repro this crash. You can easily see it going wrong by setting breakpoints on your event handlers, note how they fire over and over again before your program bombs. The explanation is a bit long winded, I'll give the short version first. The MSDN documentation for the LostFocus event gives stern warnings, both a Note and a Caution, pointing out that this is a low-level event that is dangerous. These events are also hidden in the Properties window for that reason. Fix your problem by using the Enter and Leave event instead.
The long version: the TextBox.HideSelection property is rather special. It is related to the way some properties on native Windows controls are specified. These controls are created with the CreateWindowEx() winapi function, it takes a dwExStyle and dwStyle argument, flags that specify style options for the window. The HideSelection property is such a style flag, ES_NOHIDESEL.
That presents a problem when you want to change the property. Difficult because it can only be specified when the native control is created. Winforms does something pretty heroic to deal with that limitation, it destroys the native control and re-creates it.
That can have pretty interesting side effects, to put it mildly. Most are not observable, but you do for example see the window on the screen getting destroyed and recreated. That's why it flickers. The core problem with your code is, inevitably, because the native window is getting destroyed it also loses the focus. So the LostFocus event immediately fires, right after you got the GotFocus event. Which does something unfortunate, it again changes the HideSelection property. Which forces Winforms to recreate the native control again.
This repeats over and over again when your GotFocus event handler yet again runs for the new native control. This does eventually end when Windows puts a stop to it and doesn't allow any more native windows to be created, it pulls the plug at 10,000 controls after a while. Which generates the "Error creating window handle" exception.
The Enter and Leave events should always be used for focusing events, they only fire if the user actually moved the focus, and don't fire when it happened because of other reasons, like this one. Also notable is that there's no point at all in changing the HideSelection property like you do, the property only has an affect when TextBox doesn't have the focus. The selection is never hidden when it has the focus. So the proper fix here is remove these event handlers and simply set the HideSelection property to True in the Properties window. The default value.
Cant reproduce this works for me:
private void textBox1_Leave(object sender, EventArgs e)
{
((TextBox)sender).HideSelection = false;
}
private void textBox1_Enter(object sender, EventArgs e)
{
((TextBox)sender).HideSelection = true;
}

How to check whether text input is finished

I'm developing a simple WPF application where I want to use the text changed method for a specific text field. the thing is I implemented the method but, the method gets fired in very short period, like even after i enter one character. I want to check whether the text change is completed in order to go with the methods written in the text changed method.
private void searchBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (...) // how to check whether the typing is finished?
{
// code goes here
}
}
I think you'll need the LostFocus event for this. As #SLaks comment says, you can't predict whether the user will press another key. Alternatively, you could databind the control - depending on what you're actually trying to do that may make more sense.
Instead of TextChanged, try monitoring the LostFocus event, which will fire when the user has left the textbox, either through pressing Enter/Tab or clicking somewhere else on the form.
Agree with LostFocus
UIElement.LostFocus Event
Question does not ask about binding but something to consider.
In binding the equivalent is UpdateSourceTrigger="LostFocus"
Binding.UpdateSourceTrigger Property
With binding you can get into more advanced validation UI effects.
How to: Implement Binding Validation

How can a control handle a Mouse click outside of that control?

I'm writing a custom control and I'd like the control to switch from an editing state to it's normal state when a user clicks off of the control. I'm handling the LostFocus event and that helps when a user tabs away or if they click on to another control that's Focusable. But if they don't click on something Focusable, it won't switch out of it's editing state. So I have two solutions in mind:
Walk up the tree to the top most element when it goes in to an editing state and add a handler for MouseDownEvent (and handle "handled" events). In the handler I'd kick the control out of it's editing state and remove the handler from the top most element. This seems like a bit of a hack, but it would probably work well.
Example code:
private void RegisterTopMostParentMouseClickEvent()
{
_topMostParent = this.FindLastVisualAncestor<FrameworkElement>();
if ( _topMostParent == null )
return;
_topMostParent.AddHandler( Mouse.MouseDownEvent, new MouseButtonEventHandler( CustomControlMouseDownEvent ), true );
}
private void UnRegisterTopMostParentMouseClickEvent()
{
if ( _topMostParent == null )
return;
_topMostParent.RemoveHandler( Mouse.MouseDownEvent, new MouseButtonEventHandler( CustomControlMouseDownEvent ) );
_topMostParent = null;
}
Use Mouse.PreviewMouseDownOutsideCapturedElement and add a handler to my control. In the handler I'd kick the control out of it's editing state. But I don't seem to get the event to fire. When does the Mouse.PreviewMouseDownOutsideCapturedElement get kicked off?
Example code:
AddHandler( Mouse.PreviewMouseDownOutsideCapturedElementEvent, new MouseButtonEventHandler( EditableTextBlockPreviewMouseDownOutsideCapturedElementEvent ), true );
Just to clarify the answer provided about mouse focus - it was useful but I had to do some further digging + mucking about to get something that actually worked:
I was trying to implement something like a combobox and needed similar behaviour - to get the drop down to disapear when clicking on something else, without the control having knowledge of what something else was.
I had the following event for a drop down button:
private void ClickButton(object sender, RoutedEventArgs routedEventArgs)
{
//do stuff (eg activate drop down)
Mouse.Capture(this, CaptureMode.SubTree);
AddHandler();
}
The CaptureMode.SubTree means you only get events that are outside the control and any mouse activity in the control is passed through to things as normal. You dont have the option to provide this Enum in UIElement's CaptureMouse, this means you will get calls to HandleClickOutsideOfControl INSTEAD of calls to any child controls or other handlers within the control. This is the case even if you dont subscribe to the events they are using - full Mouse capture is a bit too much!
private void AddHandler()
{
AddHandler(Mouse.PreviewMouseDownOutsideCapturedElementEvent, new MouseButtonEventHandler(HandleClickOutsideOfControl), true);
}
You would also need to hang on to + remove the handler at the appropriate points but I've left that out here for the sake of clarity/brevity.
Finally in the handler you need to release the capture again.
private void HandleClickOutsideOfControl(object sender, MouseButtonEventArgs e)
{
//do stuff (eg close drop down)
ReleaseMouseCapture();
}
Capture the mouse.
When an object captures the mouse, all mouse related events are treated as if the object with mouse capture perform the event, even if the mouse pointer is over another object.
I usually get the parent window and add a preview handler, even if already handled. Sometimes when MouseCapture is not enough, this technique comes handy:
Window.GetWindow(this).AddHandler
(
UIElement.MouseDownEvent,
(MouseButtonEventHandler)TextBox_PreviewMouseDown,
true
);
I would approach this a different way - have the form that contains the control remove focus from the control when a user clicks on another part of the form.
Having the control actually loose focus is far cleaner than attempting to have the control "simulate" focus being lost in certain situations, when in fact it hasn't. Bear in mind that unless the control has really lost focus it will still accept things like keyboard input.

How to force control to fire leave event in winforms using c#?

I am pasting text in textbox1.text and I need textbox1 should fire its leave event by itself.
For now I am using this following code. but i will appreciate if anyone can suggest me an elegant or better way:-
private void event()
{
textbox1.Text = SearchedText;
textbox1.Focus();
textbox2.Focus();
}
First I am pasting text, then setting up Focus on the control, then set up focus again on second control. It is firing leave event of textbox1, but any thing better?
Just call the code directly, no need to wait for an event:
private void textBox1_Leave(object sender, EventArgs e) {
mumble();
}
private void someEvent() {
textBox1.Text = SearchedText;
mumble();
}
void mumble() {
// etc...
}
Just calling textBox1_Leave(this, EventArgs.Empty) works fine too.
You should handle the TextChanged or Validated events instead of the Leave event.
To FORCE Leave, Validating and so on Events, no matter what, I've found ONE working solution.
First i tried:
ProcessTabStop(true);
ProcessTabStop(false);
instead of:
textbox1.Focus();
textbox2.Focus();
Problem with the TextBox 1 and 2 Focus() is that its only Active Component that needs Leave, Validating and so on fired, not other Controls, and besides, what if the form is dynamic, you as a programmer not necessarily have any idea what Control you are trying to Leave, that's why i changed Control.Focus() method to ProcessTabStop method above. The problem is then, if only ONE Control has TabStop true, there is no control to go to and back from. So Events are NOT Fired.
Next problem is that i not necessarily Close the Form with the mouse so Focus doesn't change, I use a Key (Ctrl+Enter) to Accept the Form, and then Leave, validating and so on are NOT fired, when i Send Form Close, as Form Close registers weather there are changes or not. But Values are set in Leave on TextBoxes, so I had to find a solution that worked no matter what i did to it. I almost gave up, actually i had a problem report all filled out, when I thought, what if i set ActiveControl to Null and then to the Control it came from. It worked, but had som "Flicker" due to color change on Parent Panel depending on Active or Inactive.
The "Workaround" that works in all cases is:
Control Old = ActiveControl;
// ActiveControl.SuspendLayout();
// ActiveControl.FindForm().SuspendLayout();
ActiveControl = null;
ActiveControl = Old;
// ActiveControl.FindForm().ResumeLayout();
// ActiveControl.ResumeLayout();
That seems to fire Leave, Validating and so on Events, no matter number of Form Controls and TabStopped Controls. You MAY need to SuspendLayout on either ActiveControl, or Form. My Control (Parent Panel) changes color when Active/Inactive, if I do not Suspend Layout on Form, parent panel gets an unwanted "flicker" effect.
Looking at the solution, it is very obvious, now I've found it, but took me half a day to try different things that solved one or another problem, but not all.
I know this a VERY old thread, but one of very few articles I've found on the subject of Forcing Leave Event to be Fired.

Categories

Resources