if (e.KeyCode == Keys.Enter) is non-functional - c#

I have this
private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Return)
{
var items = new[] { 500+ objects here };
if (toolStripTextBox1.Text.StartsWith("www."))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (toolStripTextBox1.Text.StartsWith("http://"))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (toolStripTextBox1.Text.StartsWith("https://"))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (items.Any(item => toolStripTextBox1.Text.Contains(item)))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
else
{
webBrowser1.Navigate("https://www.google.ca/?gws_rd=ssl#safe=active&q=" + toolStripTextBox1);
}
}
}
and it litteraly doesn't work. eg. I run it, no errors, all it does is play the windows error sound and won't be functional....
I know the code after the if statement is functional cause i have the exact same code on a button and it works just fine.

Use your code in key up event, not key down, this will make event fully executed and eligible to read the key pressed.
I have adjusted your code and it works, you don't have to use KeyChar just use KeyCode instead and it should work.
private void toolStripTextBox1_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter || e.KeyValue == (char)Keys.Return)
//if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Return)
{
var items = new[] { 500 + "objects here" };
if (toolStripTextBox1.Text.StartsWith("www."))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (toolStripTextBox1.Text.StartsWith("http://"))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (toolStripTextBox1.Text.StartsWith("https://"))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
if (items.Any(item => toolStripTextBox1.Text.Contains(item)))
{
webBrowser1.Navigate(toolStripTextBox1.Text);
}
else
{
webBrowser1.Navigate("https://www.google.ca/?gws_rd=ssl#safe=active&q=" + toolStripTextBox1);
}
}

Make sure that the control has focus, or redirect the event to the control
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown%28v=vs.110%29.aspx

Try this for your KeyPress event handler:
private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Return)
{
//Insert code here
It sounds like the problem may be that the method is not bound to the KeyPress event.
In the designer, click on the textbox, and then over to the side where it lists all of the properties, there should be a lightning bolt looking icon, click on that, and then scroll down to KeyPress and make sure it says toolStripTextBox1_KeyPress
EDIT
Alternatively, you can add the event handler programmatically. In your Form_Load event, add the code
toolStripTextBox1.KeyPress += toolStripTextBox1_KeyPress;
and in your Form_Closed event handler, add
toolStripTextBox1.KeyPress -= toolStripTextBox1_KeyPress;

Related

How to prevent call several KeyDown events by pressing a single key on the keyboard?

I have set KeyPreview property of the form to true in order to call keyboard events of the form before control events.
Both the form and the control in the form have KeyDown event like:
form:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)) {
MessageBox.Show("Control + Enter (Form)");
}
}
control:
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (!e.Control && (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)) {
MessageBox.Show("Control + Enter (TextBox)");
}
}
As you see the difference between these two parts of code is that in the form event code I need to call the KeyDown event when the user presses CTRL and Enter keys at the same time,
In the TextBox event code, I need to call the event when the user presses Enter key without holding CTRL-key.
The problem is that when I press Ctrl and Enter keys at the same time both of the above events will call.
How to prevent call both events?
I suggest you use the textBox1_KeyUp event. You can refer to the following code. My test was successful.
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return))
{
MessageBox.Show("Control + Enter (Form)");
}
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Control)
{
e.Handled = true;
}
else if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Control + Enter (TextBox)");
}
}
Use the ProcessCmdKey and like this.
protected override bool ProcessCmdKey(ref Message msg, System.Windows.Forms.Keys keyData)
{
int WM_ALRT_DOWN = 0x0104;
int WM_KEYDOWN = 0x0100;
if (msg.Msg == WM_ALRT_DOWN && (int)msg.WParam == (int)Keys.F4) //Alt + F4
{
return true; // The key is manually processed
}
if (msg.Msg == WM_KEYDOWN && (int)msg.WParam == (int)Keys.Escape) //Esc
{
return true; // The key is manually processed
}
if (msg.Msg == WM_KEYDOWN && (int)msg.WParam == (int)Keys.Space) //Space
{
return true; // The key is manually processed
}
}

C# Why is my control not accepting multiple keys in the KeyDown event

Ok guys so I've been working on this control for close to a month and one of the issues that I'm having is that if I press the CTRL key by it's self it registers and if I press the Space key by it's self it registers. I've tried to separate the two and I've tried to use them in the same if statement. Both are unsuccessful.
My first attempt was like this
protected override void OnKeyDown(KeyEventArgs e)
{
// base.OnKeyDown(e);
if (_isEditing)
{
if (e.KeyData == Keys.Delete)
{
if (_selectedObj != null)
{
DeleteSelectedObject();
}
}
}
if (e.Control && e.KeyData == Keys.Space)
{
_isEditing = !_isEditing;
Invalidate();
}
}
Now if I remove the Ctrl or the 'Space' key from the equation it works fine. So I tried to separate them and came up with
protected override void OnKeyDown(KeyEventArgs e)
{
// base.OnKeyDown(e);
if (_isEditing)
{
if (e.KeyData == Keys.Delete)
{
if (_selectedObj != null)
{
DeleteSelectedObject();
}
}
}
if (e.Control)
{
Console.WriteLine(DateTime.Now.ToShortTimeString());
if (e.KeyData.Equals(Keys.Space))
{
_isEditing = !_isEditing;
Console.WriteLine(DateTime.Now.Ticks.ToString());
}
Invalidate();
}
}
using the Console.WriteLine() as a cheater to tell me when the key is pressed and the Ticks doesn't get displayed unless I Comment out the CTRL clause. Where am I going wrong here?
Try something like
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Space)
{
}
You won't get modifier in a KeyDown event. Rather try one of the following ways to know if modifiers (Ctrl, Shift, Alt) are pressed or not:
Keyboard.IsKeyDown
if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
&& e.KeyData == Keys.Space){}
Check Keyboard.Modifiers
if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
&& e.KeyData == Keys.Space){}

How to detect control + v for pasting

I am new to C#. I am using the following code to detect Ctrl+v when pressed on the keyboard:
while(true)
{
bool check = (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl));
if (check && Keyboard.IsKeyDown(Key.V))
{
if (Clipboard.ContainsText())
history.Dispatcher.Invoke(new invoke_method2(update2),
new object[] { Clipboard.GetText(), history });
}
}
The program is running in the background. The problem is, it works when the user presses Ctrl and then v. But the conditions also stand true if the user presses v and then Ctrl, which is an unwanted trigger. Is there a way to overcome it?
To capture a shortcut in a window in WPF, implement a KeyDown event, so creating a new thread isn't necessary:
public MainWindow()
{
InitializeComponent();
KeyDown += MainWindow_KeyDown;
}
void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
{
if (e.Key == Key.V)
{
}
}
}
Edit:
If you want to go with your solution, then you're practically searching for a point in time when V isn't pressed, but Ctrl is, so the following works:
while (true)
{
if (!Keyboard.IsKeyDown(Key.V))
{
while (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
{
if (Keyboard.IsKeyDown(Key.V))
{
}
}
}
}

Unable to capture Enter Key

I have a simple form by which I take input:
12 Buttons, 1 Textbox (disabled & read-only)
this is what I do to handle input
Login_KeyDown() is common method I call for all the KeyDown of every UI component & the form itself..
private void Login_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
Application.Exit();
}
else if (e.KeyCode == Keys.NumPad9 || e.KeyCode == Keys.D9)
{
button3.BackgroundImage = Properties.Resources.button_hover;
button3.ForeColor = Color.White;
pin.Text = pin.Text + "9";
}
else if (e.KeyCode == Keys.Back)
{
button11.BackgroundImage = Properties.Resources.button_hover;
button11.ForeColor = Color.White;
if (pin.Text.Length > 0)
pin.Text = pin.Text.Substring(0, pin.Text.Length - 1);
}
else if (e.KeyCode == Keys.Enter)
{
MessageBox.Show(pin.Text);
}
}
This code works fine when I start the app but after I have clicked on any component, rest of the code works fine but "Enter Key Condition" doesn't work.
My guess is as "Enter Key Condition" is not working for UI components or something like that.
I have also tried using "Key Press Event" which uses KeyPressEventArgs then checking KeyChar == 13 but that is also not working.
What is the problem, and how can I solve it?
p.s.
I have not set any button click events for any button, the app is 100% KBoard based.
Check out PreviewKeyDown. Return raises that event on button controls.
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Return)
MessageBox.Show("I found return");
}
Or alternatively you can force it to raise those special keys in the KeyDown Event by using:
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Return)
e.IsInputKey = true;
}
More information: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown.aspx
Have you tried to use
Keys.Return
Instead
Edit:
Just thought of this. Do you have the acceptbutton set for the main form?
This is because your Form has AcceptButton defined. For example, you have a "OK", "Accept" or "Confirm" button with DialogResult set to "OK". This tells its parent form that there is an AcceptButton, and the Enter event on the form would go to this button.
What you should do is to catch the Enter key at form level. Add this code to the form:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ((this.ActiveControl == myTextBox) && (keyData == Keys.Return))
{
//do something
return true;
}
else
{
return base.ProcessCmdKey(ref msg, keyData);
}
}

How do I suppress the noise associated with pressing RETURN in a textbox?

I have read that I can suppress this noise by defining a form accept button, which is something I am trying to avoid (I can point it at a hidden or inactive button I suppose, but since it's not explicitly what I'm trying to do, I'm concerned about side effects)
I use the following snippet to trap the return key and it works just fine, the noise does not occur if I click the button manually.
private void urlTextBox_KeyDown(object sender, KeyEventArgs e) {
if ( e.KeyCode == Keys.Return )
//if ( e.KeyValue.Equals(13) )
{
e.SuppressKeyPress = true;
//e.Handled = true;
goButton.PerformClick();
}
I am targetting .NET 4.0 so I should be able to implement most ideas.
Give this a shot:
private void urlTextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
e.SuppressKeyPress = true;
}
}
private void urlTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
e.Handled = true;
goButton.PerformClick();
}
}
Source
It may also work with the KeyDown event but I haven't tested it.

Categories

Resources