C#: TextBox not receiving keys when using TextPreview on form - c#

I am implementing a search function in a windows form in c#. I have set KeyPreviewto true on the form and have added an event handler for KeyDown so I can catch things like ctrl+f, esc and enter.
I am catching these keys just fine and I'm able to make my text box appear, but I am unable to type into the box. All of the keys are going to PortsTraceForm_KeyDown(...) but they never make it to the text box. According to the msdn page about KeyPreview, setting e.Handled to false should cause the event to pass to the view in focus (the text box), but this isn't happening. I have not registered a KeyDown event for the text box, so it should be using the default behavior. Have I missed something?
KeyDown event:
private void PortsTraceForm_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
e.Handled = false;
if (e.KeyData == (Keys.F | Keys.Control)) // ctrl+f
{
e.Handled = true;
ShowSearchBar();
}
else if (e.KeyCode == Keys.Escape) // esc
{
e.Handled = true;
HideSearchBar();
}
else if (e.KeyCode == Keys.Enter) // enter
{
if (searchPanel.Visible)
{
e.Handled = true;
if (searchShouldClear)
SearchStart();
else
SearchNext();
}
}
}
show search bar:
private void ShowSearchBar()
{
FindBox.Visible = true;
FindBox.Focus(); // focus on text box
}
hide search bar:
private void HideSearchBar()
{
this.Focus(); // focus on form
FindBox.Visible = false;
}

Your TextBox likely does not have focus even though you are calling Focus(). From the documentation:
Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.
You can check the return value of Focus() for success, but I have had little luck in the past using that method to set focus to an arbitrary control. Instead, try using the method that the documentation suggests, i.e., call Select().
EDIT:
Nevermind (though it's still valid advice), I think I see your problem:
e.SuppressKeyPress = true
Why are you doing this? Again, from the docs:
[SuppressKeyPress] Gets or sets a value indicating whether the key event should be passed on to the underlying control
So you are intentionally preventing the TextBox from getting key events. If you want to pass the event through you shouldn't be setting that property to false.

try this example , of overrides method.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// your code here
// this is message example
MessageBox.Show(keyData.ToString());
return base.ProcessCmdKey(ref msg, keyData);
}
Regards.

Related

How to make Enter Key as Default key for Tab Changing for all the textbox in a Window Form C#?

I am using c# window form application. I have already tried many example on the internet for this query but nothing works for me. I just want to replace the action of Enter key with Tab key on a Window Forms. I don't want to apply keydown or up event on one by one on my textbox. I just want a single event which I can apply on my window form.
Thanks.
It works fine now I used these code of lines on form keyup event, and set the KeyPreview property True.
if (e.KeyData == System.Windows.Forms.Keys.Enter)
{
SendKeys.Send("{TAB}");
}
Create your own custom TextBox:
public class MyTextBox : TextBox
{
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Parent.SelectNextControl(this, true, true, true, true);
e.Handled = true;
e.SuppressKeyPress = true; // suppress Ding sound
}
base.OnKeyDown(e);
}
}
Compile the code. This component will appear in the toolbar. Use it instead of the regular textboxes.

Catch and process KeyPress/KeyDown without modifying text in TextBox

I currently have the following event handler which catches the Ctrl+Enter key combo in my Form code:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && e.Control)
{
// Stuff
}
}
I also have two non-ReadOnly TextBoxes in the form, one of which is multiline, while the other one isn't. Whenever I hit Ctrl+Enter, the event does get handled, but it also registers as an Enter keypress when the focus is in either TextBox. What I want to do is register the key combo without the Enter keypress modifying the text in either box. Is there any way I could go about doing this?
Your best choice is use ProcessCmdKey: Just add this to your Form add it will work:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.Enter))
{
// Stuff
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
You should use the PreviewKeyDown event instead and set the IsInputKey property accordingly:
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Enter && e.Control)
{
// Stuff
e.IsInputKey = false;
}
}
UPDATE: From the name of your handler, I guess you added it to the Form's KeyPress/KeyDown/PreviewKeyDown event. Instead you should register the method I showed above with each TextBox's PreviewKeyDown event.
To not destroy what already works for you, you may leave your code as it is and just add a handler to the TextBox's PreviewKeyDown event where you set IsInputKey to false for the specified keys, but don't do your // Stuff.

Shift + F10 in TextBox KeyDown event

I have a form with a text box.
myTB.KeyDown += new KeyEventHandler(this.myTB_KeyDown);
In this event I can get Keys.Apps to open the context menu.
Now another shortcut for context menu is Shift + F10.
Is it possible to capture that too inside the KeyDown event?
Any logic that I can implement to capture those keys?
So far what I see is, when the Shift key is pressed, that time itself the KeyDown event get's called and no way checking for both Shift and F10 together!
If I understand your question correctly, and you want to disable default Shift+F10 menu and handle those combination yourself, it's enough to handle KeyDown event and detect the combination and the set e.Handled=true;:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode== Keys.F10 && e.Shift==true)
{
//Shift + F10 pressed, do what you need.
e.Handled = true;
}
}
You can also disable the default context menu that will be shown, by setting ShortcutsEnabled property of your TextBox to false.
Here is a pretty safe way to check for shift + F10
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.F10 | Keys.Shift))
{
if (txtBox1.Focused)
{
txtBox1.Text = "Captured!";
return true;
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
Description:
This will capture every keystroke. From there is will check if the keystroke is Shift+F10, the single pipe acts like &&. After that it does a simple check to see if the textbox you are planning on having the event happen is focuses, or active control. If it fails either of those checks it sends the information of the keystrokes to return base.ProcessCmdKey(ref msg, keyData); which will give normal functionality to the keystroke without any overridden checks or whatever you may want to do with the captured keystrokes.

Does using SuppressKeyPress in a KeyDown event corrupt MaskedTextBoxes?

I'm setting SuppressKeyPress = true when a user presses the ENTER/RETURN key in a MaskedTextBox to prevent the annoying beep that is normally made. This works great, but when I clear my form the MaskedTextBox no longer behaves as expected. The first character entered is a phantom character that disappears after the 2nd character is entered.
Example:
__.___
Set text = "0"
0_.___
User enters text
09.999
User presses ENTER
User presses Save & Next (this clears the form)
Reset text = "0"
0_.___
User enters first 9
09_.___
User enters second 9
0_.9__
If the user TABS out of the MaskedTextBox instead of pressing ENTER, this works fine (the text is entered correctly without any odd shifting.) The only differences I can find are that I'm using SuppressKeyPress and that the flagState in Non-Public Members is different (2052 when I do NOT SuppressKeyPress and 2048 when I DO SuppressKeyPress.)
Is there a way to either prevent the BEEP without breaking the MaskedTextBox or a way to fix the MaskedTextBox after SuppressKeyPress (I've tried most if not all the methods on the MaskedTextBox itself: refreshText, refresh, etc...)
Here is the MaskedTextBox definition and the KeyDown method:
//
// aTextBox
//
this.aTextBox.Location = new System.Drawing.Point(130, 65);
this.aTextBox.Mask = "##.###";
this.aTextBox.Name = "aTextBox";
this.aTextBox.Size = new System.Drawing.Size(50, 20);
this.aTextBox.TabIndex = 3;
this.aTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.general_KeyDown);
this.aTextBox.Leave += new System.EventHandler(this.validate);
general_KeyDown looks like this:
private void general_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
e.SuppressKeyPress = true;
SendKeys.Send("{TAB}");
}
}
I can't repro but I definitely see it in the reference source. MaskTextBox is also looking for Keys.Enter and sets and internal flag when it sees it, a flag that affects the key handling for subsequent keystrokes. Your code may well mess this up.
Make sure that the control doesn't see the keystroke at all by overriding OnKeyDown. That requires inheriting your own control, like this:
using System;
using System.Windows.Forms;
class MyMaskTextBox : MaskedTextBox {
protected override void OnKeyDown(KeyEventArgs e) {
if (e.KeyData == Keys.Enter) {
e.Handled = e.SuppressKeyPress = true;
this.Parent.GetNextControl(this, true).Select();
return;
}
base.OnKeyDown(e);
}
}
Paste the code in a new class and compile. Drop the new control from the top of the toolbox, replacing your old one.

C# Disable the TAB key

I have this code:
this.searchInput.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.inputKeypress);
private void Keypress(object sender, KeyPressEventArgs e)
{
// If Tab has been pressed
if(122 == (int)e.KeyChar)
{
switchTab(sTab);
MessageBox.Show(sTab);
}
}
What it does is that it sets focus to another element.
But, when the focus is set to a TextBox, and I press TAB, it just makes a tab in the TextBox, and does not set focus on the next element.
Anyone got an idea how can I make this work?
I've tried to set e.Handled = true; but that didn't work...
Have you tried setting AcceptsTab on the TextBox to false?
Edit:
yep. It does not work. Strange... It still tabulates in the textbox
That makes little sense. I ran a small test app, and the tab key only brings focus away from the TextBox when its AcceptsTab and Multiline properties are both true, regardless of an event handler being defined for KeyPress.
Are you sure some other code isn't setting AcceptsTab to true? If you are, does setting Multiline to false change the tab behaviour at all? Could you post more of your relevant code?
Set the AcceptsTab property of the text box to false?
You'll need to create an instance of the control like so, and override the following methods:
using System.Windows.Forms
//optional namespace
public class NoTabTextBox : TextBox
{
protected override bool IsInputKey(Keys keyData)
{
switch (keyData)
{
case Keys.Tab:
return true;
}
return base.IsInputKey(keyData);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab) { e.Handled = true; e.SuppressKeyPress = true; }
base.OnKeyDown(e);
}
}
Build the solution, then subsitute you're regular TextBox with the new one 'NoTabTextBox', by finding it under the user controls in toolbox.
This will capture the Tab key and force it to do nothing.

Categories

Resources