I have a USB Keyboard that have some Special keys like "FN",PLAY,MUTE and one that changes the keyboard light. I was trying to get what is this key "name" to perform a logic to change the color periodically.
private void textBox1_TextChanged(object sender, EventArgs e)
{
var key = sender as TextBox;
var result = key.Text;
}
But the key its not a string to be recognized. How can I do this ? Thanks!
I will suggest you to use OnKeyPress and OnKeyDown events instead to check what was pressed. MSDN Link.
Example:
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if(e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
//If shift key was pressed, it's not a number.
if (Control.ModifierKeys == Keys.Shift) {
nonNumberEntered = true;
}
}
// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
if (nonNumberEntered == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
}
}
Related
I have a class that catches keyboard keys and I want to catch a specific combination:
Alt + 1
And in case this combination is detected to do my stuff.
This is what I have try:
private bool isAltPressed;
private bool isOnePressed;
private bool bothPressed;
private void HookManager_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.LMenu)
isAltPressed = true;
if (e.KeyCode == Keys.D1)
isOnePressed = true;
if (isAltPressed & isOnePressed)
bothPressed = true;
}
private void HookManager_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (bothPressed)
// Do something...
if (e.KeyCode == Keys.LMenu)
{
isAltPressed = false;
bothPressed = false;
}
if (e.KeyCode == Keys.D1)
{
isOnePressed = false;
bothPressed = false;
}
}
So where do I need to verify that both keys are pressed and released and then do my stuff?
Try this:
if ( e.KeyData == (Keys.Alt | Keys.D1) )
Keys is a struct having a flag attribute.
It means that several key codes can be combinated with the logic or operator to form the result.
[Flags]
public enum Keys ...
You should not wait for alt key to be released to perform your action. Unless you can explain why you need to make sure both the alt key and the key pressed must be released before 'doing something', the following code should suffice in either your KeyUp or KeyDown event.
if (e.Modifiers == Keys.Alt && e.KeyCode == Keys.D1)
{
// Do Something
}
I want to get a TextBox input key.
I was generate "KeyDown" event and
using the next
string inputKey = new KeysConverter().ConvertToString(e.KeyCode)
bun it is only assign upper case.
I want both upper case and lower case.
What should I do?
If you insist on using KeyDown Event This is what you need.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
string inputKey;
bool capsLock = IsKeyLocked(Keys.CapsLock); // Check for capslock is on
bool shift = e.Shift; // Check for Shift button was pressed
if ((shift && !capsLock) || (!shift && capsLock))
{
inputKey = new KeysConverter().ConvertToString(e.KeyCode);
}
else if ((shift && capsLock) || (!shift && !capsLock))
{
inputKey = new KeysConverter().ConvertToString(e.KeyCode).ToLower();
}
}
You should use the KeyPress event and then get the character with e.KeyChar.
For example:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}
I want to make a program to simulate textentry if user press the keys "D1 - D0" and simulate some numbers if user pressed the function keys..
Here is the code I have tried.
if (e.KeyData == Keys.D1){
SendKeys.Send("simulate this text entry");
}
if (e.KeyData == Keys.F12){
SendKeys.Send("123");
}
But the problem is when I press the F12 button, the KeyDown event identify the first "1" as the "D1" key and sends both "123" and "simulate this text entry"
How can I prevent this problem ?
When you go to send the keys, you'd have to set a flag so you know to ignore the characters being sent. Additionally, you'd need to know when to turn the flag back on. This could be done by setting a variable to the length of the value being sent, and then incrementing a counter with each detected key. This isn't foolproof as the user could hit keys in rapid succession (or hold a key down) and you wouldn't know if the keypress was a result of user interaction or from your simulation.
Here's the basic idea:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool IgnoreKeys = false;
private int target = 0;
private int counter = 0;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (!IgnoreKeys)
{
if (e.KeyData == Keys.D1)
{
Send("simulate this text entry");
}
if (e.KeyData == Keys.F12)
{
Send("123");
}
}
else
{
counter++;
if (counter == target)
{
IgnoreKeys = false;
}
}
}
private void Send(string entry)
{
IgnoreKeys = true;
counter = 0;
target = entry.Length;
SendKeys.Send(entry);
}
}
The problem is that using SendKeys.Send( ... ) there is no way your program can tell the difference between your sent keys and the user's keyboard input.
When you send the keys "123" it is the same as if the user pressed the 1, 2, and 3 keys.
Because you're listening for the 1 key, that event fires and catches the '1' sent by sendkeys.
If possible, try to append text to the content you're trying to "simulate textentry" into and avoid sendkeys.
Otherwise consider making your number hotkeys alt/ctrl-combinations such as this:
if (e.Control && e.KeyCode == Keys.D1)
{
SendKeys.Send("simulate this text entry");
e.Handled = true;
}
That will prevent this event from being fired when you press F12 and send "123" (because ctrl is not pushed).
Finally solved the problem.. :) Here is the code.. Have to use "SendKeys.Flush()" in this task...
private bool IgnoreKeys = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyData == Keys.D1) && (!IgnoreKeys))
{
SendKeys.Send("Simulate this text" + "{ENTER}");
}
if (e.KeyData == Keys.F12)
{
IgnoreKeys = true;
SendKeys.Send("123");
SendKeys.Flush();
IgnoreKeys = false;
}
This prevents the KeyDown event considering "1" in the text "123" as the key "D1"
Idea is Idle_Mind's :) Thank you..
I want a c# split container that ignores cursor keys and can only be controlled with the mouse. How can I do this? This is so I can use the keyboard input in one of the side panels without simultaneously moving the split.
Using e.Handled = true or e.SuppressKeyPress = true to prevent the keys from resizing the splitter didn't work for me.
I was able to do it by setting IsSplitterFixed = true on KeyDown, and IsSplitterFixed = false on MouseDown/MouseMove (to allow resizing by mouse).
e.g.
public Form1()
{
InitializeComponent();
splitContainer1.MouseMove += splitContainer1_MouseMove;
splitContainer1.KeyDown += splitContainer1_KeyDown;
splitContainer1.MouseDown += splitContainer1_MouseDown;
}
void splitContainer1_MouseDown(object sender, MouseEventArgs e)
{
splitContainer1.IsSplitterFixed = false;
}
void splitContainer1_MouseMove(object sender, MouseEventArgs e)
{
splitContainer1.IsSplitterFixed = false;
}
void splitContainer1_KeyDown(object sender, KeyEventArgs e)
{
splitContainer1.IsSplitterFixed = true;
}
You may disable the keyboard input handling the KeyDown event of the control and if required, you may handle the event if the input matches specific keys.
Example
splitContainer1.KeyDown += new KeyEventHandler(splitContainer1_KeyDown); //Link the KeyDown event of splitContainer1 to splitContainer1_KeyDown
private void splitContainer1_KeyDown(object sender, KeyEventArgs e)
{
// if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right) //Continue if one of the arrow keys was pressed
// {
e.Handled = true; //Handle the event
// }
}
Moreover, you may stop the splitter from moving by canceling the SplitterMoving event of the SplitContainer control according to the KeyCode gathered from its KeyDown event
Example
Keys KeyCode; //This is the variable we will use to store the KeyCode gathered from the KeyDown event into. Then, check if it matches any of the arrow keys under SplitterMoving event canceling the movement if the result was true
splitContainer1.KeyDown += new KeyEventHandler(splitContainer1_KeyDown); //Link the KeyDown event of splitContainer1 to splitContainer1_KeyDown
splitContainer1.SplitterMoving += new SplitterCancelEventHandler(splitContainer1_SplitterMoving); //Link the SplitterMoving event of splitContainer1 to splitContainer1_SplitterMoving
private void splitContainer1_SplitterMoving(object sender, SplitterCancelEventArgs e)
{
if (KeyCode == Keys.Up || KeyCode == Keys.Down || KeyCode == Keys.Left || KeyCode == Keys.Right) //Continue if one of the arrow keys was pressed
{
KeyCode = Keys.A; //Reset the KeyCode
e.Cancel = true; //Cancel the splitter movement
}
}
private void splitContainer1_KeyDown(object sender, KeyEventArgs e)
{
KeyCode = e.KeyCode; //Set KeyCode to the KeyCode of the event
// e.Handled = true; //Handle the event
}
Thanks,
I hope you find this helpful :)
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);
}
}