How do you handle a KeyDown event when the ALT key is pressed simultaneously with another key in .NET?
The KeyEventArgs class defines several properties for key modifiers - Alt is one of them and will evaluate to true if the alt key is pressed.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyData != (Keys.RButton | Keys.ShiftKey | Keys.Alt))
{
// ...
}
}
Something like:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt)
{
e.Handled = true;
// ,,,
}
}
This is the code that finally Works
if (e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z && e.Alt){
//Do SomeThing
}
I capture the alt and down or up arrow key to increment the value of a numericUpDown control. (I use the alt key + down/up key because this form also has a datagridview and I want down/up keys to act normally on that control.)
private void frmAlzCalEdit_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyCode == Keys.Down)
{
if (nudAlz.Value > nudAlz.Minimum) nudAlz.Value--;
}
if (e.Alt && e.KeyCode == Keys.Up)
{
if (nudAlz.Value < nudAlz.Maximum) nudAlz.Value++;
}
}
Create a KeyUp event for your Form or use a library like I did to get a GlobalHook so you can press these keys outside the form.
Example:
private void m_KeyboardHooks_KeyUp(object sender, KeyEventArgs e)
{
if ( e.KeyCode == Keys.Alt || e.KeyCode == Keys.X)
{
}
}
Related
I have a textbox with a OnKeyPress event. In this textbox I wish to input only numbers, and for some specific letters like t or m, I would want to execute a code without that letter being typed in the textbox. Small sample of what I am trying to do:
//OnKeyPressed:
void TextBox1KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.T || e.KeyCode == Keys.M) Button1Click(this, EventArgs.Empty);
}
This unfortunately does not prevent the input of the letter..
Set the SuppressKeyPress property from KeyEventArgs to true, like below:
private void TextBox1KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.T || e.KeyCode == Keys.M)
{
e.SuppressKeyPress = true;
Button1Click(this, EventArgs.Empty);
}
}
You could always run the TryParse on the keyDown event so as to validate as the data gets entered. It saves the user an additional UI interaction.
private void TextBox1KeyDown(object sender, KeyEventArgs e)
{
int i;
string s = string.Empty;
s += (char)e.KeyValue;
if (!(int.TryParse(s, out i)))
{
e.SuppressKeyPress = true;
}
else if(e.KeyCode == Keys.T || e.KeyCode == Keys.M)
{
e.SuppressKeyPress = true;
Button1Click(this, EventArgs.Empty);
}
}
my question is how to detect two hot keys in win form application
CTRL +C,CTRL,K like visual studio commenting command
I need to simulate VS hot key For commenting a line of code
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.C)
{
}
}
Simple way is... There is a Windows API Function called ProcessCmdKey, by overriding this function we can achieve what we want
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Control | Keys.C)) {
MessageBox.Show("You have pressed the shortcut Ctrl+C");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Microsoft Documentation can be found here
source
private bool _isFirstKeyPressedW = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control & e.KeyCode == Keys.W)
{
_isFirstKeyPressedW = true;
}
if (_isFirstKeyPressedW)
{
if (e.Control & e.KeyCode == Keys.S)
{
//write your code
}
else
{
_isFirstKeyPressedW = e.KeyCode == Keys.W;
}
}
}
if you want to handle Ctrl + C followed by Ctrl+ K you need to maintain a state variable.
Set the Form KeyPreview property to true and handle the Form KeyDown event.
Try This:
this.KeyPreview=true;
private bool isFirstKeyPressed= false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
isFirstKeyPressed = true;
}
if (isFirstKeyPressed)
{
if (e.Control && e.KeyCode == Keys.K)
{
MessageBox.Show("Ctrl+C and Ctrl+K pressed Sequentially");
/*write your code here*/
isFirstKeyPressed= false;
}
}
}
I made a method that detects when a key is pressed, but its not working! Heres my code
void KeyDetect(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W && firstload == true)
{
MessageBox.Show("Good, now move to that box over to your left");
firstload = false;
}
}
I also tried to make a keyeventhandler but, it sais "cannot assign to key detect because it is a method group"
public Gwindow()
{
this.KeyDetect += new KeyEventHandler(KeyDetect);
InitializeComponent();
}
Use keypress event like this:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyCode == Keys.F1 && e.Alt)
{
//do something
}
}
1) Go to your form's Properties
2) Look for the "Misc" section and make sure "KeyPreview" is set to "True"
3) Go to your form's Events
4) Look for the "Key" section and double click "KeyDown" to generate a function to handle key down events
Here is some example code:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
Console.WriteLine("You pressed " + e.KeyCode);
if (e.KeyCode == Keys.D0 || e.KeyCode == Keys.NumPad0)
{
//Do Something if the 0 key is pressed (includes Num Pad 0)
}
}
You are looking for this.KeyPress. See How to Handle Keypress Events on MSDN.
Try to use the KeyDown event.
Just see KeyDown in MSDN
Just do
if (Input.GetKeyDown("/* KEYCODE HERE */"))
{
/* CODE HERE */
}
How can I determine in KeyDown that ⇧ + Tab was pressed.
private void DateTimePicker_BirthDate_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && e.Modifiers == Keys.Shift)
{
//do stuff
}
}
can't work, because never both keys are pressed exactly in the same second. You always to at first the Shift and then the other one..
It can't work, because never both keys are pressed exactly in the same second.
You're right that your code doesn't work, but your reason is wrong. The problem is that the Tab key has a special meaning - it causes the focus to change. Your event handler is not called.
If you use a different key instead of Tab, then your code will work fine.
If you really want to change the behaviour of Shift + Tab for one specific control, it can be done by overriding ProcessCmdKey but remember that many users use the Tab key to navigate around the form and changing the behaviour of this key may annoy those users.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (DateTimePicker_BirthDate.Focused && keyData == (Keys.Tab | Keys.Shift))
{
MessageBox.Show("shift + tab pressed");
return true;
}
else
{
return base.ProcessCmdKey(ref msg, keyData);
}
}
If you are looking for a key press combination (Tab, then Shift) like Ctrl K + D you will have to use this modified example which was taken from MSDN social.
private StringBuilder _pressedKeys = new StringBuilder();
private void DateTimePicker_BirthDate_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab)
{
_pressedKeys.Append("Tab");
return;
}
if (e.Modifiers == Keys.Shift)
{
_pressedKeys.Append("Shift");
return;
}
if (_pressedKeys.ToString()."TabShift")
{
MessageBox.Show("It works!");
_pressedKeys.Clear();
}
else
{
_pressedKeys.Clear();
}
base.OnKeyDown(e);
}
First hook the Tab keypress event, then during the event, check the state of the Shift key. Keep in mind that there are two shift keys; make sure you check both of them.
This very related post shows how to check the state of modifier keys:
How to detect the currently pressed key?
Edit: an insight provided by another answerer who justly deserves an upvote is that the default behavior of the tab key (to change control focus) must be suppressed.
You can find your answer in
this post
It's Simple.
You can do that using KeyUp Event in the TextBox
private void txtBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && e.Shift == false) // TAB Key Pressed
{
}
if (e.KeyCode == Keys.Tab && e.Shift == true) // TAB + SHIFT Key Pressed
{
}
}
Or
Using this you can identify Any Key is press inside the form
//Add This code inside the Form_Load Event
private void Form1_Load(object sender, EventArgs e)
{
this.KeyUp += new System.Windows.Forms.KeyEventHandler(KeyPressEvent);
this.KeyPreview = true;
}
//Create this Custom Event
private void KeyPressEvent(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && e.Shift == false) // TAB Key Pressed
{
}
if (e.KeyCode == Keys.Tab && e.Shift == true) // TAB + SHIFT Key Pressed
{
}
}
It's Simple.
Using this you can identify Any Key is press inside the form
//Add This code inside the Form_Load Event
private void Form1_Load(object sender, EventArgs e)
{
this.KeyUp += new System.Windows.Forms.KeyEventHandler(KeyPressEvent);
this.KeyPreview = true;
}
//Create this Custom Event
private void KeyPressEvent(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && e.Shift == false) // TAB Key Pressed
{
}
if (e.KeyCode == Keys.Tab && e.Shift == true) // TAB + SHIFT Key Pressed
{
}
}
I have a control with KeyDown and KeyUp events as shown below. The problem I am having is that 'x' is TRUE in KeyDown but always FALSE in KeyUp. I am trying to detect the Alt key (as you may have guessed).
Is there a gottcha that I don't know. I mean, when I press Alt it detects it ok but on keyup it's false.
Any suggestions/ideas
Thanks
private void MyControl_KeyDown(object sender, KeyEventArgs e)
{
bool x;
x = ((int) (e.KeyData & Keys.Alt) != 0);
x = (e.KeyData & Keys.Alt) == Keys.Alt;
x = e.Alt;
}
private void MyControl_KeyUp(object sender, KeyEventArgs e)
{
bool x;
x = ((int) (e.KeyData & Keys.Alt) != 0);
x = (e.KeyData & Keys.Alt) == Keys.Alt;
x = e.Alt;
}
Are you trying to detect an Alt+[letter] event? Is so, try this:
private void YourControl_KeyDown(object sender, KeyEventArgs e)
{
if((e.Alt) & (e.KeyCode == Keys.X))
{
MessageBox.Show("Alt-X pressed");
}
}
For just Alt, try this:
private void YourControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Menu)
{
//YourCode
e.Handled = true;
}
}
private void YourControl_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Menu)
{
//YourCode
e.Handled = true;
}
}
I hope you're not just setting a bool member variable in your class in response to the Alt key being pressed.
If you want to know if the Alt key is down while executing code in response to other events (eg mouse events) use the Control.ModifierKeys property as it is far more reliable. It also means you don't have a redundant member variable.
If you are actually trying to detect if the user has pressed just a Modifier key by itself then #bluecoder's solution is probably what you want.
If you want detect real key pressing (Alt or any other key), you can use this code. This code works in the KeyUp, KeyDown and other key events
private void YourControl_KeyDown(object sender, KeyEventArgs e)
{
Key _key = e.Key != Key.System ? e.Key : e.SystemKey;
// _key is your real pressed key
}