WPF always focus on a textbox - c#

I want to always Focus on a specific TextBox on my WPF application whenever I click on anything on the application it should always focus on the TextBox.

Add to the TextBox.OnLostFocus event a handler which sets the focus to the TextBox.

There is an event handler MouseLeftMouseButton. When the event handler was triggered, use textbox.Focus() inside the handler.

If i'm right, your intention is to get the keyboard commands and display the char pressed into your textbox even if the focus is on other controls.
If that is the case, you can route the keyboard commands to the root control (control in the top level... eg: window), analyse them and display in the textbox. I'ld try to give examples if that helps.
EDIT:
private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (Keyboard.Modifiers != ModifierKeys.Shift)
{
if (e.Key > Key.A && e.Key < Key.Z)
{
textBox1.Text += e.Key.ToString().ToLower();
}
}
else
{
if (e.Key > Key.A && e.Key < Key.Z)
{
textBox1.Text += e.Key.ToString();
}
}
e.Handled = true;
}

Related

Use Up/Down keys to scroll a ListBox when a TextBox has focus without moving cursor

I have a TextBox that a user can type a search term into and a ListBox that displays results. There is also a button will display some information based on the item selected on click.
I'm trying to scroll through the listbox using the up and down arrow keys so the user doesn't have to click the item, then the button. At that point I might as well just rely on the double click event to do the work since they are already on the item. However, I'm trying to make this more "keyboard only friendly".
The following code works, but with one minor flaw:
private void txtSearchTerm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down && Results.SelectedIndex < (Results.Items.Count - 1))
{
Results.SelectedIndex++;
}
else if (e.KeyCode == Keys.Up && Results.SelectedIndex > 0)
{
Results.SelectedIndex--;
}
}
With this code, the cursor still moves left and right along with the selected item changing. I want it to remain where it is (not forcing it to the end). I didn't have any luck with the txtSearchTerm.Select(...) event, but I guess I could have missed something...
There is a TextChanged event, but it only calls to a search function I wrote that populates the list box as the user types, so I will leave that code out for simplicity.
Am I missing something or overlooking some method to make this TextBox/ListBox combo function how I'm intending?
Quick note: If you've ever used UltraEdit, I'm trying to mimic the behavior of that configuration window, basically.
You should use e.Handled = true; to cancel using the key that you processed:
private void txtSearchTerm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
if (Results.SelectedIndex < (Results.Items.Count - 1))
Results.SelectedIndex++;
e.Handled = true;
}
else if (e.KeyCode == Keys.Up)
{
if (Results.SelectedIndex > 0)
Results.SelectedIndex--;
e.Handled = true;
}
}
I set e.Handled = true; if the key is Keys.Down or Keys.Up regardless of the SelectedIndex to completely disable moving caret using those keys.

WPF TextBox I would like to add a undo / redo like the command prompt when the up and down arrow keys are pushed

I would like to add the functionality that is found in the command line prompt into my WPF TextBox. In the command propmpt when the user pushes the up arrow the previous command that was used will appear. And if he keeps pushing the up arrow the next previous text will be seen. And if the user pushes down then it will go the other way again.
What would be the best way to accomplish this? (The built in redo / undo works more on a document level than what I am requiring.)
You can use Undo e Redo Application Commands.
This is the MVVM not compliant version:
In your XAML
<TextBox Margin="5" PreviewKeyUp="TextBox_PreviewKeyUp" AcceptsReturn="False" />
In your code-behind
private List<string> _history = new List<string>();
private int _historyIndex = -1;
private void TextBox_PreviewKeyUp(object sender, KeyEventArgs e)
{
TextBox textBox = (TextBox)sender;
if (e.Key == Key.Return)
{
_history.Add(textBox.Text);
if (_historyIndex < 0 || _historyIndex == _history.Count - 2)
{
_historyIndex = _history.Count - 1;
}
textBox.Text = String.Empty;
return;
}
if (e.Key == Key.Up)
{
if (_historyIndex > 0)
{
_historyIndex--;
textBox.Text = _history[_historyIndex];
}
return;
}
if (e.Key == Key.Down)
{
if (_historyIndex < _history.Count - 1)
{
_historyIndex++;
textBox.Text = _history[_historyIndex];
}
return;
}
}
I hope this is the functionality you meant.
You could simply use the PreviewKeyDown event and check for Key.Down or Key.Up and read a List of your last commands. If you set e.Handled = true the cursor don't jump up.
private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Up)
{
e.Handled = true;
//Here comes the code where you read your last commands and print it to your Textbox
}
//Same for Key.Down
}
To make it MVVM-compliant you can use an eventtrigger which triggers a command in your Viewmodel.
Hope this gives you the idea. Unfortunately I haven't enough time to program for you. :)
You can persist commands into stack collection.

TextBox KeyPress event doesn't fire

I have a Form with nine TextBox controls. Each one has a KeyPress event handler that fires on Enter/Return and more.
The fifth TextBox(Kategorie) and sixth (Ort) don't fire. The others do. The code is:
private void tb_Kategorie_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show("works");
if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Return)
{
tb_Ort.Focus();
}
else if (e.KeyChar == (char)Keys.Escape)
{
tb_Kategorie.Text = escSpeicher;
tb_Kategorie.SelectAll();
}
}
The event handler is set in the Designer and in designer.cs. The button and the code are not copy/pasted. Can someone tell me where the problem is?
// You Can Use Key Down method here
private void tb_Kategorie_KeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show("works");
if (e.KeyCode== Keys.Enter || e.KeyCode== Keys.Return)
{
tb_Ort.Focus();
}
else if (e.KeyCode== Keys.Escape)
{
tb_Kategorie.Text = escSpeicher;
tb_Kategorie.SelectAll();
}
}
// try this
Try to set the Form.KeyPreview property to True
It is something with the Autocomplete Source.
This is the same problem like in
Autocomplete on Combobox onkeypress event eats up the Enter key
It is not really solved, but a nice workaround

WPF how to manipulate tab sequence by setting index?

Now imagine I have ten controls all bound inside a stackpanel.
By default, when TAB is pressed, the focus will move from control 1 subsequently to control 10.
Now what I want is, after focus moving from control 1 to control 2, when the user press TAB again, the focus will go back to control 1. So far I can only mess around with the sequence by using KeyboardNavigation.TabIndex="N" where N = "0,1,2,3,..", but what I ultimately want is skipping the remaining 8 controls.
Please do not suggest TabNavigation="NONE" or IsTabStop="False" to skip the control, I don't want to mess with other controls and yea, I'm fine with hardcode sequence.
Override the preview key down event on the controls that you want to have control over and if its tab then do what you want.
Here is an example if it was something like a textbox you could use something like this. Atach the event handlers either in c# or in the xaml.
btn1.PreviewKeyDown += new KeyEventHandler(btn1_KeyDown);
btn2.PreviewKeyDown += new KeyEventHandler(btn2_KeyDown);
then
private void btn1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab && (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
{
//do what you want when shift+tab is pressed.
e.Handled = true;
}
else
{
btn2.Focus();
e.Handled = true;
}
}
private void btn2_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab && (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
{
//do what you want when shift+tab is pressed.
e.Handled = true;
}
else
{
btn1.Focus();
e.Handled = true;
}
}

C# - How to override actions for "Up arrow" and "Down arrow" for a textbox?

I have a textbox and below it i have a listbox.
While the user is typing in the textbox if he presses the up or down arrow he should make a selection in the listbox. The textbox detects all the characters (except space) but it seems that it can't detect the arrow presses.
Any solution for this? This is a WPF project btw.
EDIT, Here's the working code thanks to T.Kiley:
private void searchBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.IsDown && e.Key == Key.Down)
{
e.Handled = true;
//do your action here
}
if (e.IsDown && e.Key == Key.Up)
{
e.Handled = true;
//do another action here
}
}
I just tried this and it works. Add a preview key down event to the textbox
private void TextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.IsDown && e.Key == Key.Down)
MessageBox.Show("It works");
}
You can listen to they KeyDown event of the TextBox. In the handler, check whether the arrow key was pressed (you might need to listen to key up to avoid triggering your code multiple times if the user holds down the button for too long).
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
// Do some code...
}
}

Categories